I’m developing a website that utilizes PHP to check the live status of streams from various platforms. However, I’ve encountered significant issues with long loading times, and occasionally the server times out.
My script frequently hits the 30-second execution time limit and results in the following error: Fatal error: Maximum execution time of 30 seconds exceeded.
Here’s my function for determining if a stream is live:
function checkStreamStatus($streamName, $platform){
if($platform == 'twitch'){
$apiEndpoint = "https://api.twitch.tv/api/streams/" . $streamName;
$request = file_get_contents($apiEndpoint);
$jsonResponse = json_decode($request, true);
return $jsonResponse['stream'] != null;
} else if($platform == 'youtube'){
$streamCheckUrl = 'https://api.youtube.com/check/' . $streamName;
$response = file_get_contents($streamCheckUrl);
$parsedResponse = json_decode($response, true);
return $parsedResponse['status'] == "live";
}
}
I also have another function for fetching stream details:
function fetchStreamDetails($streamName, $platform){
$streamName = sanitizeInput($streamName);
$platform = sanitizeInput($platform);
if($platform == 'twitch'){
$streamData = json_decode(file_get_contents("https://api.twitch.tv/streams/$streamName"),true);
return array(
'thumbnail'=>$streamData['preview']['medium'],
'stream_title'=>$streamData['channel']['status'],
'preview'=>$streamData['preview']['large'],
'category'=>$streamData['game']
);
} else if($platform == 'youtube'){
$streamData = json_decode(file_get_contents("https://api.youtube.com/live/$streamName"),true);
return array(
'thumbnail'=>$streamData['snippet']['thumbnails']['medium']['url'],
'stream_title'=>$streamData['snippet']['title'],
'preview'=>$streamData['snippet']['thumbnails']['high']['url'],
'category'=>$streamData['snippet']['categoryId']
);
}
}
Although the functions are working properly, their execution speed is concerning. I’ve noticed that other gaming websites can load similar data much quicker. Any suggestions on improving my script’s performance?