# Trying to use php to find if a channel is live

**URL:** <https://discuss.dev.twitch.com/t/trying-to-use-php-to-find-if-a-channel-is-live/30534>\
**Category:** API\
**Created:** [February 19, 2021, 3:31pm UTC](https://discuss.dev.twitch.com/t/trying-to-use-php-to-find-if-a-channel-is-live/30534 "2021-02-19T15:31:02Z")\
**Posts on this page:** 7\
**Page:** 1

<div class="post-metadata">

**Author:** ![raythgaming](https://avatars.discourse-cdn.com/v4/letter/r/4491bb/32.png) [@raythgaming](https://discuss.dev.twitch.com/u/raythgaming)\
**Post date:** [February 19, 2021, 3:31pm UTC](https://discuss.dev.twitch.com/t/trying-to-use-php-to-find-if-a-channel-is-live/30534/1 "2021-02-19T15:31:02Z")

</div>

So basically I want to write a php script that will run periodically to see if a channel is live. i have the following code:

```
<?php
$client_id = 'lqhpxo5cq53rbp2pzmb71qjlusqsw2';//Twitch client id AKA: api key
$user = 'raythgaming';//Streamers username
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.twitch.tv/helix/streams?user_login=$user");//Endpoint
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    "Client-ID: $client_id"//Add auth
));
$profile_data = json_decode(curl_exec($ch), true);
curl_close($ch);
print_r($profile_data);

if (!isset($profile_data['data'][0])) {
    $live = 0;//Not live
} else {
    $live = 1;//Is live
}

if ($live == 1) {
    $title = $profile_data['data'][0]['title'];
    $viewer_count = $profile_data['data'][0]['viewer_count'];
    $game_id = $profile_data['data'][0]['game_id'];
    $went_live_at = DateTime::createFromFormat("Y-m-d H:i:s", date("Y-m-d H:i:s", strtotime($profile_data['data'][0]['started_at'])))->format('Y-m-d H:i:s');
    $started = date_create($went_live_at);
    $now = date_create(date('Y-m-d H:i:s'));
    $diff = date_diff($started, $now);
    $hours = $diff->h;
    $minutes = $diff->i;
    echo "<br/>$user is playing $game_name, started streaming $hours hours $minutes minutes ago and has $viewer_count viewers TITLE: $title";
} else {
    echo "<br/>$user is not live";
}

```

When I run this I’m getting:

> Array ( [error] =\> Unauthorized [status] =\> 401 [message] =\> OAuth token is missing )  
> raythgaming is not live

I’ve tried looking through the docs and cannot for the life of me work out how to get an OAuth token to add into the headers which I know how to do fine.

---

<div class="post-metadata">

**Author:** ![BarryCarlyon](https://d3ovvz0v2ajtpu.cloudfront.net/user_avatar/discuss.dev.twitch.com/barrycarlyon/32/253_2.png) [@BarryCarlyon](https://discuss.dev.twitch.com/u/BarryCarlyon)\
**Post date:** [February 19, 2021, 3:33pm UTC](https://discuss.dev.twitch.com/t/trying-to-use-php-to-find-if-a-channel-is-live/30534/2 "2021-02-19T15:33:48Z")

</div>

Your code doesn’t generate a token at all.

For this sort of application an App Access Token is appropriate

> **[Getting OAuth Access Tokens](https://dev.twitch.tv/docs/authentication/getting-tokens-oauth/)**
>
> Getting OAuth Access Tokens

You should generate, store, and reuse the token (until it expires) and use that Token with your code, it’s a Simple curl POST request before you do touy Streams call.

Example that will do this, and store the token in a `json` file in the same directory [https://github.com/BarryCarlyon/twitch\_misc/blob/master/authentication/app\_access\_tokens/php/generate\_and\_maintain\_token.php](https://github.com/BarryCarlyon/twitch_misc/blob/master/authentication/app_access_tokens/php/generate_and_maintain_token.php)

---

<div class="post-metadata">

**Author:** ![raythgaming](https://avatars.discourse-cdn.com/v4/letter/r/4491bb/32.png) [@raythgaming](https://discuss.dev.twitch.com/u/raythgaming)\
**Post date:** [February 19, 2021, 3:36pm UTC](https://discuss.dev.twitch.com/t/trying-to-use-php-to-find-if-a-channel-is-live/30534/3 "2021-02-19T15:36:43Z")

</div>

Thank you i’ve been at this for hours. In the dev console does it matter if I use [https://localhost](https://localhost) as the redirect URL if I’m hosting this script on my website?

---

<div class="post-metadata">

**Author:** ![BarryCarlyon](https://d3ovvz0v2ajtpu.cloudfront.net/user_avatar/discuss.dev.twitch.com/barrycarlyon/32/253_2.png) [@BarryCarlyon](https://discuss.dev.twitch.com/u/BarryCarlyon)\
**Post date:** [February 19, 2021, 3:37pm UTC](https://discuss.dev.twitch.com/t/trying-to-use-php-to-find-if-a-channel-is-live/30534/4 "2021-02-19T15:37:22Z")

</div>

> [@raythgaming](#):
>
> In the dev console does it matter if I use [https://localhost](https://localhost) as the redirect URL if I’m hosting this script on my website?

For App Access tokens, a redirect URI is irrelevant. It’s only used for “regular”/user access tokens, so you can leave it as localhost.

---

<div class="post-metadata">

**Author:** ![raythgaming](https://avatars.discourse-cdn.com/v4/letter/r/4491bb/32.png) [@raythgaming](https://discuss.dev.twitch.com/u/raythgaming)\
**Post date:** [February 19, 2021, 3:49pm UTC](https://discuss.dev.twitch.com/t/trying-to-use-php-to-find-if-a-channel-is-live/30534/5 "2021-02-19T15:49:57Z")

</div>

Ok so I’ve got the following code now:

[code]\<?php  
$client\_id = “lqhpxo5cq53rbp2pzmb71qjlusqsw2”;  
$secret\_id = “MYSECRETID”;  
$keys = false;  
if (file\_exists( **DIR**. ‘/auth.json’)) {  
$keys = json\_decode(file\_get\_contents( **DIR**. ‘/auth.json’));  
}

$generate\_token = true;  
if ($keys) {  
// validate the token

```
$ch = curl_init('https://id.twitch.tv/oauth2/validate');
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Authorization: OAuth ' . $keys->access_token
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$r = curl_exec($ch);
$i = curl_getinfo($ch);
curl_close($ch);

if ($i['http_code'] == 200) {
    // the token appears good
    $generate_token = false;

    // optional to check the expires
    $data = json_decode($r);
    if (json_last_error() == JSON_ERROR_NONE) {
        if ($data->expires_in < 3600) {
            // less than an hour left
            // make a new token
            echo 'Token close to expire. Regenerate';
            $generate_token = true;
        }
    } else {
        echo 'Failed to parse JSON. Assume dead token';
        $generate_token = true;
    }
}

```

} else { $generate\_token = true; }

if ($generate\_token) {  
$ch = curl\_init(‘[https://id.twitch.tv/oauth2/token](https://id.twitch.tv/oauth2/token)’);  
curl\_setopt($ch, CURLOPT\_RETURNTRANSFER, 1);  
curl\_setopt($ch, CURLOPT\_POST, true);  
curl\_setopt($ch, CURLOPT\_POSTFIELDS, array(  
‘client\_id’ =\> $client\_id,  
‘client\_secret’ =\> $secret\_id,  
‘grant\_type’ =\> “client\_credentials”  
));

```
$r = curl_exec($ch);
$i = curl_getinfo($ch);
curl_close($ch);

if ($i['http_code'] == 200) {
    $data = json_decode($r);
    if (json_last_error() == JSON_ERROR_NONE) {
        echo 'Got token';
        print_r($data);

        // store the token for next run
        file_put_contents( __DIR__. '/auth.json', $r, JSON_PRETTY_PRINT);
    } else {
        echo 'Failed to parse JSON';
    }
} else {
    echo 'Failed with ' . $i['http_code'] . ' ' . $r;
}

```

} else {  
echo ‘Token OK’;  
print\_r($keys);  
}

$user = ‘raythgaming’;//Streamers username  
$ch = curl\_init();

curl\_setopt($ch, CURLOPT\_URL, “[https://api.twitch.tv/helix/streams?user\_login=$user](https://api.twitch.tv/helix/streams?user_login=%24user)”);//Endpoint  
curl\_setopt($ch, CURLOPT\_RETURNTRANSFER, TRUE);  
curl\_setopt($ch, CURLOPT\_HTTPHEADER, array(  
“Client-ID: $client\_id”,  
"Authorization: Bearer "+$keys-\>access\_token  
));  
$profile\_data = json\_decode(curl\_exec($ch), true);  
curl\_close($ch);  
print\_r($profile\_data);

if (!isset($profile\_data[‘data’][0])) {  
$live = 0;//Not live  
} else {  
$live = 1;//Is live  
}

if ($live == 1) {  
$title = $profile\_data[‘data’][0][‘title’];  
$viewer\_count = $profile\_data[‘data’][0][‘viewer\_count’];  
$game\_id = $profile\_data[‘data’][0][‘game\_id’];  
$went\_live\_at = DateTime::createFromFormat(“Y-m-d H:i:s”, date(“Y-m-d H:i:s”, strtotime($profile\_data[‘data’][0][‘started\_at’])))-\>format(‘Y-m-d H:i:s’);  
$started = date\_create($went\_live\_at);  
$now = date\_create(date(‘Y-m-d H:i:s’));  
$diff = date\_diff($started, $now);  
$hours = $diff-\>h;  
$minutes = $diff-\>i;  
echo “  
$user is playing $game\_name, started streaming $hours hours $minutes minutes ago and has $viewer\_count viewers TITLE: $title”;  
} else {  
echo “  
$user is not live”;  
}  
[/code]

I’m still getting no OAuth even though I have a token (I checked):

Token OKstdClass Object ( [access\_token] =\> \*\*\*\*\*\*\* [expires\_in] =\> 5196723 [token\_type] =\> bearer ) Array ( [error] =\> Unauthorized [status] =\> 401 [message] =\> OAuth token is missing )  
raythgaming is not live

---

<div class="post-metadata">

**Author:** ![BarryCarlyon](https://d3ovvz0v2ajtpu.cloudfront.net/user_avatar/discuss.dev.twitch.com/barrycarlyon/32/253_2.png) [@BarryCarlyon](https://discuss.dev.twitch.com/u/BarryCarlyon)\
**Post date:** [February 19, 2021, 3:51pm UTC](https://discuss.dev.twitch.com/t/trying-to-use-php-to-find-if-a-channel-is-live/30534/6 "2021-02-19T15:51:24Z")

</div>

> [@raythgaming](#):
>
> "Authorization: Bearer "+$keys-\>access\_token

PHP uses a `.` to concantente, you just tied to do math and got an unexpected header

You should be using

```
"Authorization: Bearer " . $keys->access_token

```

---

<div class="post-metadata">

**Author:** ![system](https://d2opxh93rbxzdn.cloudfront.net/original/2X/0/05909729875cce3b53e59d5561c4d23bb14948fc.png) [@system](https://discuss.dev.twitch.com/u/system)\
**Post date:** [March 21, 2021, 3:51pm UTC](https://discuss.dev.twitch.com/t/trying-to-use-php-to-find-if-a-channel-is-live/30534/7 "2021-03-21T15:51:25Z")

</div>

Closed on March 21, 2021, 3:51pm UTC

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