user3220962 user3220962 - 2 months ago 23
PHP Question

Twitch API Include a Cleint ID with php

Got a couple PHP scripts that query the Twitch API for certain informations.
However Twitch made a change and from now on you have to include a Client ID or your request doesnt get through.

My scripts look like this:

$url = "https://api.twitch.tv/kraken/users/" . $_GET['username'] . "/follows/channels/" . $_GET['channel'];

$result = file_get_contents($url);
$result = json_decode($result, true);

#echo $result["created_at"];
#echo date('d-m-Y h:i:s ',strtotime($result["created_at"]));


$followdate = new DateTime(date('d-m-Y h:i:s',strtotime($result["created_at"])));
$heute = new DateTime(date('d-m-Y h:i:s'));
$diff = $followdate->diff($heute);


with some research i found a website tha tprovides some help with PHP and client IDs. i found this example on how to include it:

<?php
$channelsApi = 'https://api.twitch.tv/kraken/channels/';
$channelName = 'twitch';
$clientId = 'axjhfp777tflhy0yjb5sftsil';
$ch = curl_init();

curl_setopt_array($ch, array(
CURLOPT_HTTPHEADER => array(
'Client-ID: ' . $clientId
),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_URL => $channelsApi . $channelName
));

$response = curl_exec($ch);
curl_close($ch);
?>


But im not sure how to emerge this example into mine. In the exampel there is a Channel username and im confused if i have to do the scripts for each channel since right now the scripts are accessed by more than one channel.

Scripts are requested with: URL/scripts/followageTEST.php?username=XY&channel=XY

Would apreciate any help ^-^

Answer

The code you found is using curl to make a request which can include HTTP headers into request. In your situation you can't do that, because your using file_get_contents function which can only fetch the contents of a file or website.

According to the readme of Twitch API on github:

In situations where headers cannot be set, you can also specify a client ID as a querystring parameter: client_id=[CLIENT_ID]

Here is a code that should work:

$client_id = 'YOUR CLIENT ID';
$url = "https://api.twitch.tv/kraken/users/" . $_GET['username'] . "/follows/channels/" . $_GET['channel'] . '?client_id=' . $client_id;

$result = file_get_contents($url);
$result = json_decode($result, true);

#echo $result["created_at"];
#echo date('d-m-Y h:i:s  ',strtotime($result["created_at"]));

$followdate = new DateTime(date('d-m-Y h:i:s',strtotime($result["created_at"])));
$heute = new DateTime(date('d-m-Y h:i:s'));
$diff = $followdate->diff($heute);
Comments