Check if a streamer live on twitch (PHP)

I use this code

<?php
				$streamer = 'Test123';
				function is_channel_live($channel) {
					$request = json_decode(@file_get_contents( 'https://api.twitch.tv/kraken/streams/' . $channel ));
					return ( ! is_null( $request->stream ) ) ? TRUE : FALSE;
				}
				if(is_channel_live($streamer))
					echo "Is streaming";
				else
					echo "Is not streaming";
			?>

But it doesnt work
Notice: Trying to get property of non-object …

You need to send a client ID with your requests or else it will return error: bad request; status: 400; message: No client id specified

You can get a client ID by registering an application at https://dev.twitch.tv/dashboard/apps

Also, just a tip. It’s best to use cURL instead of file_get_contents because file_get_contents doesn’t return any errors as cURL would.

Thank u

Can you give me cURL example to do this?

Check out this post by /u/matt_thomas on how to replace file_get_contents with cURL.

1 Like

I have added the API version in my cURL headers. See below:

<?php

/* file_get_contents replaced with curl function - Add this function and replace any use of file_get_contents with file_get_contents_curl */

function file_get_contents_curl($url) {
$curlHeader = array(
“Client-ID: 352ei7jf3jq2mu6jvvovjy4qwv6huc”, /* SET CLIENT ID HERE */
“Accept: application/vnd.twitchtv.v5+json”
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_AUTOREFERER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_HTTPHEADER, $curlHeader);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}

?>

2 Likes

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.