Twitter Application Auth Sample - PHP

This is a sample PHP code which can be used to get a Twitter OAuth token for use in making API calls.

It includes a trends available request that gets the list of countries for which Twitter trends are available.

Be sure to read the documentation at the link above. A given application can only have one token at any given time, so once established, the token should be stored and reused.


        $consumerKey = '-- YOUR CONSUMER KEY --';
        $consumerSecret = '-- YOUR CONSUMER SECRET --';
        $encodedKey = urlencode($consumerKey);
        $encodedSecret = urlencode($consumerSecret);
        $bearerTokenCredentials = $encodedKey.':'.$encodedSecret;
       
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, 'https://api.twitter.com/oauth2/token');
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, 'grant_type=client_credentials');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_ENCODING, 'gzip');
        curl_setopt($ch, CURLOPT_HTTPHEADER,
                array('Content-Type: application/x-www-form-urlencoded;charset=UTF-8',
                        'Authorization: Basic '.$base64BearerTokenCredentials));
        $result = curl_exec($ch);
        $error = curl_errno($ch);
        if ($error === 0) {
                $json = json_decode($result);
                curl_setopt($ch, CURLOPT_URL, 'https://api.twitter.com/1.1/trends/available.json');
                curl_setopt($ch, CURLOPT_HTTPGET, true);
                curl_setopt($ch, CURLOPT_POST, false);
                curl_setopt($ch, CURLOPT_HTTPHEADER,
                                array('Authorization: Bearer '.$json->access_token));
                $result = curl_exec($ch);
                $error = curl_errno($ch);
                curl_close($ch);
                if ($error === 0) {
                        $json = json_decode($result);
                        $countries = array();
                        foreach ($json as $location) {
                                if ($location->placeType->name == 'Country') {
                                        $countries[$location->woeid] = $location->name;
                                }
                        }
                        asort($countries);
                }
        }