Go Back   GIDForums > Computer Programming Forums > MySQL / PHP Forum > PHP Code Library
User Name
Register FAQ Members List Calendar Search Today's Posts Mark Forums Read
Thread Tools Search this Thread Rate Thread
Old 21-Jan-2017, 05:59
kevinhng86 kevinhng86 is offline
New Member
Join Date: Jan 2017
Posts: 1
kevinhng86 is on a distinguished road

Connect To Twitter API For Get Request - PHP

One day when I was browsing a forum, 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 @ 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.
<blockquote class="gr1">
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& 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.

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, <strong>we have to encode the hex value to base64</strong> 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 Create a new apps. In the web field you can just put 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.

<?php class faiTwitFrame{ /* Copyright notice. * Original author kevinhng86 @ FAI Hosting Solution. * A copy of this script can be found on my blog @ * 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 view from the link below. * * This framework is a sample of how to connect to the Twitter API to get username by input user ID or get user ID by input username * Obtain your twitter API by create an App in twitter Platform and obtain an API key. * Twitter may change or update the structure of their API therefore from time to time this framework might have to be update. */ private static $ckey = ""; //Consumer Key private static $csec = ""; //Consumer Key Secret private static $okey = ""; //Oauth Key private static $osec = ""; //Oauth Key Secrect # This will check if there is a curl function or not. If there is not a curl function for php to use the script will die. # checkCurl can only be call by this class. 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 function is to send the get request to the twitter api or any website. # It's takes in 3 parameter. The url variable name is http. The header array, variable name rheaders. The param string which is pstring. private function get($http, $rheaders, $pstring ){ self::checkCurl(); # Check to see if curl exist. $ch = curl_init(); # Initialise curl into variable name ch as the handler # Declare a result array, this is use for extending this function and is not in use currently $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 variable response $response = curl_exec( $ch ); // These option here is un-neccessary currently but can be use for extending function of the future $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 curl request curl_close ($ch); # Return the variable response which hold the raw response text from the get request. # Depend on what type of server response, if we are dealing with json we will have to convert this data json return $response; } # This function is to combine two object array into one array of string value. # Each array will store the key name plus an equal sign and the key value in string format. public function dataToArray($obj1, $obj2){ $outobj = array(); # This is the return array. $outobji = 0; # This is the counter for the out array # First we cycle through the first object and each key we find. # We insert the key name plus the equal sign plus key value in string format into the outobj array. foreach ($obj1 as $key => $value){ $outobj[$outobji] = $key . "=". $value; $outobji = $outobji + 1; }; # We do the similar here by cycling through 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 platform requires this because 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 require that you have to send a unique ID for each session that you connect to Twitter API. # This function is to generate a unique sessionid for each session. # At the time of this writting the sessionID is not return, however this can be store as history record and security purpose private function sessionId(){ # alpha variable contain a string of alphabet character and will randomly be grab to generate a session id. $alpha = "abcdefghijlkmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; $length = 30; # The length of the session id. $idstr= ""; # The string variable that will be use to combine all the random letters. for ($i = 0 ; $i < $length; $i++){ # generate a random number and use that to as the position to grab a character from the alpha variable. # Notice how you have to minus 1 of the length of the string. It is because string position start at 0 and not 1. # So the string that 50 in length the 1st position is 0 and the last position is 49. $idstr .= $alpha[rand(0, strlen($alpha) - 1 )]; } return $idstr; } # This function convert string to binary format # The original php function to convert a string to binary have it limitation how many character it can do. # This function is limitted to how much a string can hold. # This 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; } # This function is to convert hex to binary. # The original function in php can only convert 40 character of hex, anything more will produce all 0. # This function can convert as much as a string can hold. private function hexTobin($hex) { $hexarr = array(); # This array is where we store the input hex string. We will split the string into small chunk $output = ""; # The output string $length = 8; # The length of each chunk $hexarr = str_split($hex, $length) ; # Split the hex string into an array. for ($i = 0; $i < count($hexarr) ; $i++ ){ $temp = base_convert($hexarr[$i], 16, 2); # Convert hex into binary # PHP hex converter will leave out begining 0 until the first 1. # This is fine in normal circumstances, however since we have to join the string together. # We need all the 0s. We know that each hex character if convert to true binary would have to be four binary. # Thus we pad to the left 0 to make up the missing string length # Then we join the string 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 into binary. # Then divide the binary string into 6 block chunk. # If the last block is not 6 in length add 0 to the right of it. # Convert each binary block to decimal. # Use that decimal number at a position to find a character in a uniformly defined characters. # The map variable represent all the characters and their position that are use in hex64 encode. # Each block of binary is then represent by a character. # After combining all the block or represent character together you then add the = sign to the end of the string. Which is the 64 position on the 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 hex and it is the same as the previous function in principle. # Only differences now is hex have to be convert instead of string. 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); //sprintf('%0'. $length .'d', $binarray[count($binarray) - 1]); } 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){ $sessionid = self::sessionId(); # create a unique session id. $timestamp = time(); # create a timestamp in unix format of current 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 current for oauth_version. $urlenc = urlencode($url); # encode the url into percent sign $sortarray = self::dataToArray($oauthheader,$params); # produce the data string array asort($sortarray); # Sort the array. Twitter requires that you have to short the key $requeststring = urlencode(self::getRequestString($sortarray)); # Encode the request string into percent sign $basestring = $method . "&" . $urlenc . "&" . $requeststring; # The base string is the method, the encoded url and the encoded request string join together and separate with an &. $signedkey = self::$csec . "&" . self::$osec; # singed key is customer secret plus the oauth secret join together with an & in the middle. $signedhash = hash_hmac("SHA1", $basestring, $signedkey); # Twitter requires that you signed the whole request string with your signed key. hmac signed and return this as a hex value. $signedhash = self::encodehex($signedhash); #Twitter requires that the sign hash must be encode in base64 from hex value to base64 $authheader = "OAuth"; #The OAuth header format is "OAuth name="value", name2="value" foreach ($oauthheader as $key => $value){ $authheader .= " " . $key . '=' . '"' . $value . '"' . ',' ; #Base on the format we build the header } $authheader .= " oauth_signature=" . '"' . urlencode($signedhash) . '"'; #As the end of the oauth header we have to our signature and it have to be url encoded. # We build the request header and return it. Notice that it is not JSON for content type ande 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 username or userid 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 param contain user_id return screen_name(username). # If param contain screen_name then return 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'] ;}; }}; # The below is test cases. $Params = faiTwitFrame::nameOrIdParam("webdothosting"); //replace webdothosting with you desire twitter username or ID. $Result = faiTwitFrame::faiTwitGateway("GET", "", $Params); $Params1 = faiTwitFrame::nameOrIdParam("190405401"); //replace webdothosting with you desire twitter username or ID. $Result1 = faiTwitFrame::faiTwitGateway("GET", "", $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>

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are Off
[IMG] code is On
HTML code is Off
Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
#1 responsive WHMCS templates since 09 | WHMCS - Wordpress - HTML5 - PHP | Welcome Fu zomex Member Announcements, Advertisements & Offers 0 08-Jun-2016 03:29
7 Tips to stay relevant on Twitter Asher ross Search Engine Optimization Forum 5 01-Sep-2013 23:52
17 Succesful keys for marketing on Twitter Asher ross Search Engine Optimization Forum 0 17-Aug-2012 10:07
PHP in HTML jrobbio Web Design Forum 4 24-Jul-2003 06:05
All the big PHP script collections that matter jrobbio MySQL / PHP Forum 5 06-Jun-2003 16:14

Network Sites: GIDNetwork · GIDApp · GIDBlog · Learning Journal by J de Silva, The

All times are GMT -6. The time now is 04:59.

vBulletin, Copyright © 2000 - 2018, Jelsoft Enterprises Ltd.