How To Connect To Twitter API – Get Request – PHP

One day when I was browsing the forum @ http://forumweb.hosting/ I saw a friend that is on my friend list who was working on a project. He was trying to integrate a form in his website where visitor could simply input their screen_name and it will tell them their user_id vice versa. I seen that post and it’s got me very interest in working with the Twitter API. I had never worked with the Twitter API before that day.

So first I went to Twitter website and look at Twitter documentation @ https://dev.twitter.com/oauth/overview/authorizing-requests. I was able to understand the procedure of how to connect to the Twitter API. From then I wrote the source code for this framework that can be extend into many more feature and function.

From the Twitter documentation it stated that what need to be collect in the OAuth request header. Those are Consumer key, Nonce(unique session id), Signature, Signature method, Timestamp, Token, Version.

This is a quote from Twitter of how to build a header string.


To build the header string, imagine writing to a string named DST.

Append the string “OAuth ” (including the space at the end) to DST.
For each key/value pair of the 7 parameters listed above:
Percent encode the key and append it to DST.
Append the equals character ‘=’ to DST.
Append a double quote ‘”’ to DST.
Percent encode the value and append it to DST.
Append a double quote ‘”’ to DST.
If there are key/value pairs remaining, append a comma ‘,’ and a space ‘ ‘ to DST.
Pay particular attention to the percent encoding of the values when building this string. For example, the oauth_signature value of tnnArxj06cWHq44gCs1OSKk/jLY= must be encoded as tnnArxj06cWHq44gCs1OSKk%2FjLY%3D.

Another requirement to connect to the Twitter API is you have to build a signature base string. From Twitter documentation I can summarise on how to create a signature base string. To build a signature base string you first have a HTTP request method which is either GET or POST. You would then append an & to the end of that. Then you join that with the encoded Twitter API URL of whichever you connecting to. Then you append to the end of the string the & character and finally you join that with the param string. The param string is consistence of the OAuth request header and the actual request params. Their name must be short in alphabetical order. At this state you produce the base string without the signing key.

POST&https%3A%2F%2Fapi.twitter.com%2F1%2Fstatuses%2Fupdate.json&include_entities%3Dtrue%26oauth_consumer_key%3Dxvz1evFS4wEEPTGEFPHBog%26oauth_nonce%3DkYjzVBB8Y0ZFabxSWbWovY3uYSQ2pTgmZeNu2VS4cg%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1318622958%26oauth_token%3D370773112-GmHxMAgYyLbNEtIKZeRNFsMKPR9EyMZeS9weJAEb%26oauth_version%3D1.0%26status%3DHello%2520Ladies%2520%252B%2520Gentlemen%252C%2520a%2520signed%2520OAuth%2520request%2521

POST&EncodedURL&ShortedParamString // This is the short example of it.

To get the signing key, the consumer secret key is added to Oauth token secret and separate by an & character. This below is a sample from Twitter. The consumer key must be in front of the Oauth token secret.

kAcSOqF21Fu85e7zjz7ZN2U4ZRhfV3WpwPAoE3Z7kBw&LswwdoUaIvS8ltyTt5jkRh4J50vUPVVHtR2YPi5kE

After that we would have to HMAC SHA1 encode the base string using the signing key. The result from an HMAC SHA1 encryption will be a hex string. We then need to convert this hex string to base64 encode. The most important subject here is that, we have to encode the hex value to base64 but not the character representation. Once we have the signing key we append it into the OAuth header and we can send the request. Much of this information can be found in the comment contain within the source code below.

To test the script you need to go https://apps.twitter.com/. Create a new apps. In the web field you can just put http://example.com or something similar. Remember to change this when you actually running the script and host it on a website.

After you create the app. Click on it and you will need to get 4 things from Twitter. The consumer key, the consumer key secret, oauth token and oauth token secret. Once you put these parameter into the script you can test it.

This is merely just a function call to demonstrate how the Twitter PHP work. You would need to wrap your code around this still. In the script I set up test cases to demonstrate in the very bottom of the script. You can modify it to the necessary need.

Advertisement

<?php
        
class faiTwitFrame{
/* Copyright notice.
 * Original author kevinhng86 @ FAI Hosting Solution.
 * A copy of this script can be found on my blog @ http://kevinhng86.iblog.website
 * This is free to use for any purpose that is not unlawful for free of charge.
 * This script follow CDDL-1.0 license protocol, to use this script for any purpose you are agreeing to CDDL-1.0.
 * CDDL-1.0 license can be found at the link below.
 * https://opensource.org/licenses/CDDL-1.0
 * This framework is a sample of how to connect to the Twitter API to get a username by inputting a user ID or get a user ID by inputting a username.
 * Obtain your twitter API key by creating an App on the Twitter Platform.
 * Twitter may change or update the structure of their API. Therefore, from time to time this framework might have to be updated.
 */

    private static $ckey = ""; # Consumer Key
    private static $csec = ""; # Consumer Key Secret
    private static $okey = ""; # Oauth Key 
    private static $osec = ""; # Oauth Key Secrect

    # This function is to evaluate if the curl function exists in the working PHP environment. If the curl function is not available, the program will exit.
    private function checkCurl(){
        if( !function_exists("curl_init") && !function_exists("curl_setopt") && !function_exists("curl_exec") && !function_exists("curl_close") ) die("Curl php library function does not exist"); else return ;
    }
        
    # This private get() function is to send the get requests to the Twitter Api.
    # The get() function can be customize to send get requests to other website.
    # The get() function requires 3 arguments for input, the url, the header array, and a param request string. 
    private function get($http, $rheaders, $pstring){
        self::checkCurl();
        $ch = curl_init();  
    
        # Declaring a result array, this is for future uses of extending this function. This result array is not currently use.
        $result = array( 'header' => '', 'header_size' => '', 'body' => '', 'curl_error' => '', 'http_code' => '', 'last_url' => ''); 
    
        # Set the url by combining the url with a ? and the param string. 
        curl_setopt($ch, CURLOPT_URL, $http . "?" . $pstring );
    
        # Set the header by inputing the array header into CURL_HTTPHEADER set function.
        curl_setopt($ch, CURLOPT_HTTPHEADER, $rheaders);
    
        # Set return transfer to true.
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    
        # Executing the request and store the response text into the variable response.
        $response = curl_exec( $ch );
    
        # These options here is un-neccessary currently but can be use for extending this function for others purpose.
        $result['header_size'] = curl_getinfo($ch,CURLINFO_HEADER_SIZE);;
        $result['header'] = substr($response, 0, $result['header_size']);
        $result['body'] = substr( $response, $result['header_size'] );
        $result['http_code'] = curl_getinfo($ch,CURLINFO_HTTP_CODE);
        $result['last_url'] = curl_getinfo($ch,CURLINFO_EFFECTIVE_URL);
        $result['curl_error'] = curl_error( $ch );
        # End un-necessary
    
        # Close the connection.
        curl_close ($ch);
    
        # Return the variable response which holds the raw response text from the get request.
        # Depend on the type of server response, this data may need to be converted.
        return $response;
    }      
        
    # This function is to combine two object array into one array of strings.
    # Each array will store the key name plus an equal sign and the key value in string format.
    public function dataToArray($obj1, $obj2){
        # This is the return array.
        $outobj = array(); 
        # This is the counter for the out array.
        $outobji = 0; 
        # First we cycle through the first object.
        # For each key we found, we insert the key's name plus the equal sign plus the key's value in string format into the outobj array.
        foreach ($obj1 as $key => $value){
            $outobj[$outobji] = $key . "=". $value;
            $outobji = $outobji + 1;
        }

        # We apply the similar procedures above to the second array.
        foreach ($obj2 as $key => $value){
            $outobj[$outobji] = $key . "=" . $value;
            $outobji = $outobji + 1;
        }     
        return $outobj;
    }

    # This function take in an array of request string and build into one string.
    # Twitter requires that you need to encode all the request, method and uri in a string format and signed the entire request.
    public function getRequestString($arr){
        $outstr = "";
        foreach ($arr as &$value){
            $outstr .= $value . "&";
        }
        $outstr = substr_replace($outstr ,"",-1);
        return $outstr;
    }
    
    # Twitter requires that you have to send a unique ID for each session that you connect to the Twitter API.
    # This function is to generate a unique session ID for each session.
    # At the time of this writing, the sessionID is not returned.
    # However, this can be customized to store the session ID for security purpose.
    private function sessionId(){
        # alpha variable contain a string of alphabet character.
        # Random numbers would be generated and their value is use as a position to get a character from the alpha string.  
         $alpha = "abcdefghijlkmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
        # The length of the session id.
         $length = 30;
        # The string variable that will be use to combine all the random letters.
         $idstr= ""; 
        for ($i = 0 ; $i < $length; $i++){ 
            # Generate a random number and use the value as the position to grab a character from the alpha string.
            $idstr .= $alpha[rand(0, strlen($alpha) - 1 )]; 
        }
        return $idstr;
    }
     
     # strToBin() function will convert a string with ASCII character to binary.
     # The original php function to convert a string to binary have a limitation how many characters the function can handle.
     # strToBin() function limited to how much a string can hold.
     # strToBin() function convert one character at a time to binary.
    private function strToBin($input){
        if (!is_string($input))
            return false;
        
        $ret = '';
        for ($i = 0; $i < strlen($input); $i++)
        {
            $temp = decbin(ord($input{$i}));
            $ret .= str_repeat("0", 8 - strlen($temp)) . $temp;
        }
        return $ret;
    }

    # hexTobin() is for converting a hexadecimal string to a binary value in string format.
    # The original function in PHP can only convert 40 characters of hexadecimal in a string.
    # PHP's function will turn string that longer that 40 characters of hexadecimal into an all zero digit binary string.
    # hexTobin() function can convert as much as a string can hold.
    # hexTobin() is a wrapper of PHP base_convert() function.
    private function hexTobin($hex) {
        # This array is where we would store the input hexadecimal string. We will split the string into smaller chunks.
        $hexarr = array();
        # The output string
        $output = "";
        # The length of each chunk.
        $length = 8;  
        # Split the hex string into an array.
        $hexarr = str_split($hex, $length) ;  

        for ($i = 0; $i < count($hexarr) ; $i++ ){
            # Convert hexadecimal value into binary value.
            $temp = base_convert($hexarr[$i], 16, 2); 
            # PHP hexadecimal converter will leave out the begining 0 until the first 1. 
            # This is fine  in a normal circumstance. 
            # However, since we have to join the strings together.
            # We need all the zero. We know that each hexadecimal digit if convert to a true binary value would have to be be four digits of binary.
            # Thus we pad to the left 0 to make up the missing string length
            # Then we join the strings together.
            $output .= str_pad($temp, strlen($hexarr[$i]) * 4 ,"0" , STR_PAD_LEFT); 
        }
        return $output;            
    }
    
    # This is a base64 encode function.
    public function encode($word){
            # Base 64 encode is to convert a string of characters into a binary value.
            # Then divide the binary string into 6 digits block chunk.
            # If the last block of digits is not six in length, add zero to the right of the string until the string is six digits in length.
            # Convert each binary block to decimal.
            # Use that decimal number at a position to find a character in a uniformly defined character string.
            # The map variable represents all the characters that are used in a hex64 encoded string.
            # Each block of binary digits is represented by a character. 
            # After combining all the block of representing character together, the = sign is added to the end of the string. Which is the 64 position on the character map.
        
            $length = 6 ; 
            $map = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=" ;
            $binword = self::strToBin($word); 
            $binarray = str_split($binword, $length);
            $str = "";

            if ( strlen($binarray[count($binarray) - 1]) < $length ){
                $binarray[count($binarray) - 1] =  str_pad($binarray[count($binarray) - 1], $length, "0", STR_PAD_RIGHT); 
            }
            
            for($i = 0; $i < count($binarray) ; $i++ ){
                $str .= $map[ bindec($binarray[$i]) ];
            }
            $str = $str . $map[64] ;
            return $str;
            
    }
    
    # This is base64 encode for hexadecimal and it is the same as the previous function in principle.
    # Only differences now is the hexadecimal value would be converted instead of the string value.
    private function encodehex($hex){
        $length = 6 ; $map = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=" ;
        $binhex = self::hexToBin($hex); $binarray = str_split($binhex, $length);
        $str = "";

        if ( strlen($binarray[count($binarray) - 1]) < $length ){

            $binarray[count($binarray) - 1] =  str_pad($binarray[count($binarray) - 1], $length, "0", STR_PAD_RIGHT);
        }
            
        for($i = 0; $i < count($binarray) ; $i++ ){
            $str .= $map[ bindec($binarray[$i]) ];
        }
        $str = $str . $map[64] ;
        return $str;            
    }
    
    
    # Building the Twitter header
    private function buildTwitHeader($method, $url, $params){
        # Create a unique session id.
        $sessionid = self::sessionId();
        # Create a timestamp in unix format of the current time;
        $timestamp = time(); 
        $output;
        $oauthheader = array("oauth_consumer_key" => self::$ckey, 
                             "oauth_nonce" => $sessionid,
                             "oauth_signature_method" => "HMAC-SHA1", # Set crypting to HMAC-SHA!
                             "oauth_timestamp" => $timestamp,
                               "oauth_token" => self::$okey,
                               "oauth_version" => "1.0"); # This is version 1.0 the current version for oauth_version.

        # Encode the url into the percent sign format
           $urlenc = urlencode($url);
           # Convert the data into an array of strings.
        $sortarray = self::dataToArray($oauthheader,$params);
        # Sort the array. Twitter requires that you have to short the keys.
        asort($sortarray);
        # Encode the request string into the percent sign format.
        $requeststring = urlencode(self::getRequestString($sortarray));
        # The base string would be the method, the encoded url and the encoded request string join together and separate with an &.
        $basestring = $method . "&" . $urlenc . "&" . $requeststring;
        # Singed key is the customer secret plus the oauth secret join together with an & in the middle.
        $signedkey = self::$csec . "&" . self::$osec;
        # Twitter requires that you signed the whole request string with your signed key. then hmac signed and return this as a hexadecimal value.
        $signedhash = hash_hmac("SHA1", $basestring, $signedkey);
        #Twitter requires that the signed hash must be encode in a base64 format, from hexadecimal value to base64 value.
        $signedhash = self::encodehex($signedhash);
        #The OAuth header format is "OAuth name="value", name2="value"
        $authheader = "OAuth"; 
        foreach ($oauthheader as $key => $value){
            $authheader .= " " . $key . '=' . '"' . $value . '"' . ',' ; #Base on the format we  would built the header.          
        } 
        
        # At the end of the oauth header, we have to add our signature and the signature has to be url encoded.
        $authheader .= " oauth_signature=" . '"' . urlencode($signedhash) . '"';  
         
        # We built the request header and return it. Notice that it is not JSON for content type and is www-form-urlencoded.
        $requestheaders = ["Content-Type: application/x-www-form-urlencoded", 
                           "Authorization: ".  $authheader, 
                           "User-Agent: FAI Hosting Solution API Client"];
        return $requestheaders;
    }
    
    # This function is to build the param string for the get request.
    private function buildTwitParamString($params){
        $paramstring = "";
        foreach ($params as $key => $value){ 
            $paramstring .= $key . "=" . $value . "&" ;
        }
        $paramstring = substr_replace($paramstring ,"",-1);
        return $paramstring;
    }
        
        # This is a public function. Check to see if the params contain a username or a user ID.
    public function nameOrIdParam($str){
        $str = trim($str); $str = trim($str, "@"); $param = "";
        if (ctype_digit($str)){
            $param = array("user_id" => $str);
        }
        if (!ctype_digit($str)){
            $param = array("screen_name" => $str);
        }
        return $param;
    }
    
  
    # This is the public function and is the entry point of the faiTwitFrame program.
    public function faiTwitGateWay($method, $url, $params){

        # Build the header.
        $header = self::buildTwitHeader($method,$url,$params);
    
        # Build the param string.
        $ps = self::buildTwitParamString($params);

        # Call and send the request. 
        $output = self::get($url, $header, $ps);
    
        # Turn the output into JSON format
        $output = json_decode($output, true);       
    
        # For now return value base on, if the param contain a user_id then return the screen_name(username).
        # If param contain a screen_name then return the user_id
        if ( array_key_exists("user_id",$params) == true  ){ return $output['screen_name'] ;};
        if ( array_key_exists("screen_name",$params ) == true  ){ return $output['id'] ;};
    }
}



# Test cases.
# Replace webdothosting with you desire twitter username or ID.
$Params = faiTwitFrame::nameOrIdParam("webdothosting");
$Result = faiTwitFrame::faiTwitGateway("GET", "https://api.twitter.com/1.1/users/show.json", $Params);


# Replace webdothosting with your desire Twitter's username or user ID.
$Params1 = faiTwitFrame::nameOrIdParam("190405401");  
$Result1 = faiTwitFrame::faiTwitGateway("GET", "https://api.twitter.com/1.1/users/show.json", $Params1);


?>

<html>

<titile>Sample of how to use Twitter Api to Get Username | Written by Kevin from Fai Hosting Solution</title>
<body>
<?php
echo '<b>'. $Result. '</b>';
echo '<br/>';
echo '<b>'. $Result1. '</b>';
?>
</body>
</html>

This post was written by Kevin and was first post @ http://kevinhng86.iblog.website.
Original Post Name: "How To Connect To Twitter API – Get Request – PHP".
Original Post Link: http://kevinhng86.iblog.website/2017/01/18/connect-to-twitter-api-for-get-request-php/.

Advertisement


Random Article You May Like

One thought on “How To Connect To Twitter API – Get Request – PHP

  1. obviously like your web site however you need to ccheck the
    spelling on several of your posts. Many of them are rife with spelling problems and I in finding it very troublesome to inform thee
    truth then again I will surely come back again.

Leave a Reply

Your email address will not be published. Required fields are marked *

*
*