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.

PHP

$consumerKey '-- YOUR CONSUMER KEY --';
        $consumerSecret '-- YOUR CONSUMER SECRET --';
        $encodedKey urlencode($consumerKey);
        $encodedSecret urlencode($consumerSecret);
        $bearerTokenCredentials $encodedKey.':'.$encodedSecret;
       
        $ch curl_init();
        curl_setopt($chCURLOPT_URL'https://api.twitter.com/oauth2/token');
        curl_setopt($chCURLOPT_POSTtrue);
        curl_setopt($chCURLOPT_POSTFIELDS'grant_type=client_credentials');
        curl_setopt($chCURLOPT_RETURNTRANSFERtrue);
        curl_setopt($chCURLOPT_HEADERfalse);
        curl_setopt($chCURLOPT_ENCODING'gzip');
        curl_setopt($chCURLOPT_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($chCURLOPT_URL'https://api.twitter.com/1.1/trends/available.json');
                curl_setopt($chCURLOPT_HTTPGETtrue);
                curl_setopt($chCURLOPT_POSTfalse);
                curl_setopt($chCURLOPT_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);
                }
        }