Using Curl in PHP

I am working on a project to help me learn how to use curl

through PHP

. I am trying to get data from Twitch-API

using my own account for testing.

I have successfully authenticated my account to my domain using:


I removed client_id

, redirect_uri

and state

to show the link I was using.

After successful authentication, it goes back to the domain that I specify ( redirect_uri

), after it goes back to that domain, the website only knows the authentication key that is generated after it is accepted by the user, from under the yoke.

Auth example: 3ofbaoidzkym72ntjua1gmrr66o0nd

Now I would like to be able to get the username, there is documentation there :

curl -H 'Accept: application/vnd.twitchtv.v3+json' -H 'Authorization: OAuth <access_token>' \


I'm trying to do it in PHP, but I don't understand the curl function ... Here's what I have so far:

<?php if(isset($_GET['code']) && isset($_GET['scope'])) { ?>

    $auth = $_GET['code'];
    $twitch = curl_init();

    $headers = array();
    $headers[] = 'Accept: application/vnd.twitchtv.v3+json';
    $headers[] = 'Authorization: OAuth ' .$auth;
    curl_setopt($twitch, CURLOPT_HEADER, $headers);
    curl_setopt($twitch, CURLOPT_URL, "");


<?php }; ?>


When I try to run this section of code, I get some errors:

HTTP/1.1 401 Unauthorized
Server: nginx
Date: Sat, 08 Aug 2015 13:43:51 GMT
Content-Type: application/json; charset=utf-8
Content-Length: 89
Connection: keep-alive
Status: 401 Unauthorized
X-API-Version: 3
WWW-Authenticate: OAuth realm='TwitchTV'
Cache-Control: max-age=0, private, must-revalidate
Vary: Accept-Encoding
X-UA-Compatible: IE=Edge,chrome=1
X-Request-Id: 4bc2e0bfadf6817366b4eb19ab5751bf
X-Runtime: 0.007862
Accept-Ranges: bytes
X-Varnish: 1641121794
Age: 0
Via: 1.1 varnish
X-MH-Cache: rails-varnish-5cb970; M

{"error":"Unauthorized","status":401,"message":"Token invalid or missing required scope"}


But I'm not sure how to fix this issue, as it seems to me that I / did everything the documentation says to do ...

How can I solve this problem?


It seems to work if I ask to use the twitch username :

curl -H 'Accept: application/vnd.twitchtv.v3+json' \


My code for using username:

$auth = urlencode($_GET['code']);
$twitch = curl_init();

$headers = array();
$headers[] = 'Accept: application/vnd.twitchtv.v3+json';
#$headers[] = 'Authorization: OAuth ' .$auth;
curl_setopt($twitch, CURLOPT_HTTPHEADER , $headers);
curl_setopt($twitch, CURLOPT_URL, "");



But I wouldn't know the user's username, unless I get it from the statement that generates the error and stores it in the database.


Reading in the documentation is more, it requires a scope as well as an access token. I was able to get the following:


    [0] => Accept: application/vnd.twitchtv.v3+json
    [1] => Authorization: OAuth code=scn89zerug002sr6r95z9ngbxmd0d2&scope=user_read+channel_read+channel_subscriptions+user_subscriptions+channel_check_subscription


But I am still getting the error ...


So I read the documentation EVEN MORE and now I figured out:

class twitch {
    var $base_url = "";
    var $client_id = "...";
    var $client_secret = "...";
    var $return_url = "...";
    var $scope_array = array('user_read','channel_read','channel_subscriptions','user_subscriptions','channel_check_subscription');

    public function get_access_token($code,$state) {
        $ch = curl_init($this->base_url . "oauth2/token");
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        $fields = array(
             'client_id' => $this->client_id,
             'client_secret' => $this->client_secret,
             'grant_type' => 'authorization_code',
             'redirect_uri' => $this->redirect_url,
             'code' => $code
        curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
        $data = curl_exec($ch);
        $response = json_decode($data, true);

        echo "<pre>".print_r($this->redirect_url,true)."</pre>";
        echo "<pre>".print_r($response,true)."</pre>";

        return $response["access_token"];

$auth = new twitch();


But this time there is another mistake, stating that mine 'redirect_uri' => $this->redirect_url

is different from the one held by the twitch.

    [error] => Bad Request
    [status] => 400
    [message] => Parameter redirect_uri does not match registered URI


I even copied and pasted from the twitch site to my variable and vice versa, I still get the same error ... Now I'm even more stuck, but at least a step closer.


source to share

1 answer

That's right, I'm going to do it with you the way I do it: d I could get one user so far, the reason you are getting errors is because you are not setting any curl parameters. I taught myself to use this which I found MASSIVELY helpful when learning curl. The code itself is basic, but so easy to read. I managed to figure it out and make it 100% harder: D

First of all, I'll show you how I got the test user. What you want to do is set the parameters, I'll stick with a simple method first.



. You can set your url using init function.

curl_setopt($twitch,CURLOPT_HTTPHEADER,array('Accept: application/vnd.twitchtv.v3+json'));//must be an array.


This will give you your test user and hopefully show you a little about what you are doing wrong. If you want to use an array method, then you must use your curl parameters as the array key so that the set function knows what to set how. (don't ask me how it all technically works: S)

I'll update to show you how to get authorization and details as soon as I process it. But basic principles: you need to send post data and set CURLOPT_POST

to true and include postdata CURLOPT_POSTFIELDS

, which should be a json array since your application requires json, I suppose?

Anyway the array:

curl_set_opts($twitch,array(CURLOPT_HEADER=>array('Accept: application/vnd.twitchtv.v3+json',CURLOPT_RETURNTRANSFER=true));


Seeing as you already know how to authorize a user, I will skip this bit, although I would recommend using something more secure than $_GET

. Maybe session variable would be a little better.

To get a specific user using the returned Auth. You want to do something like this: (Sorry, I can't test it myself, I don't have a twitch dev account)

curl_setopt($twitch,CURLOPT_HEADER,array('Accept: application/cvd.twitchtv.v3+json','Authorization: OAuth '.$_SESSION['token']));
//don't forget to close! 



This should work, although I have no idea how you get the oAuth token lol

if you want to be a really cool programmer 8 | I would recommend making several classes for this. Like this

class twitch{
    private static$details;
    public function __construct($code,$state){
    protected function makeCall($extention,$auth=false,$object=true){
            $opts=array(CURLOPT_HEADER=>array('Accept: application/cvd.twitchtv.v3+json','Authorization: OAuth '.$this->token),CURLOPT_RETURNTRANSFER=>true);
    protected function userDetails(){
    public function user(){




All Articles