PHP - Convert Twitter Id to Username or Vice Versa

kevinhng86

Member
Registered
Joined
Jan 12, 2017
Messages
58
Points
0
Hello all,

From a request of a friend that needed help to convert Twitter username to user Id or User Id to username, I spend sometime written this library of function that can help anyone need to connect to the twitter Api to translate username to id or vice versa. Although this is not a very long script it's however really complicated to explain for right now. I may explain this in the future but for now I can show you how to use the script. 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 was a really great project and yes I did learned a couple new things from this one project so in the end, I do have to thank you for giving me the idea. Sorry I didn't have the time to make this into a interactive form or similar. This merely just a function call in PHP. You would need to wrap your code around this still. In the script I already set it up so in the way you can kind of understand how it would work.

Updated to the code. Update code now also have tutorial and the code been modified for easy extending it's function.

Code:
<?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 view from 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 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", "https://api.twitter.com/1.1/users/show.json", $Params);



$Params1 = faiTwitFrame::nameOrIdParam("190405401");  //replace webdothosting with you desire twitter username or ID.
$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>
 
Last edited:

FerdieQO

Well-known member
Joined
Jul 15, 2016
Messages
213
Points
28
Cool kevinhng86!

I tested your codes in this case

Code:
$Params = nameOrIdParam("forumwebhosting"); //replace webdothosting with you desire twitter username or ID.
$Result = faiTwitGateway("GET", "https://api.twitter.com/1.1/users/show.json", $Params);
And it showed the result and worked as what I wanted.

twitter-id-to-username.png

I also tested with the case inserting Twitter username into this line and it also worked.

Code:
$Params = nameOrIdParam("forumwebhosting");
But when I tried these lines in your code

Code:
$Params = nameOrIdParam("forumwebhosting"); //replace webdothosting with you desire twitter username or ID.
$Result = faiTwitGateway("GET", "https://api.twitter.com/1.1/users/show.json", $Params);

$Param1 = nameOrIdParam("190405401"); //replace webdothosting with you desire twitter username or ID.
$Result1 = faiTwitGateway("GET", "https://api.twitter.com/1.1/users/show.json", $Params1);
Code:
<?php
echo '<br>';
echo '<br>Testing with Twitter Username: forumwebhosting';
echo '<br>';
echo '<br>';
echo 'The result is: <b>'. $Result. '</b>';


echo '<br>';
echo '<br>Testing with Twitter ID: 190405401';
echo '<br>';
echo '<br>';
echo 'The result is: <b>'. $Result1. '</b>';

?>
then it didn't work. Mean that I want to see both results at a time by assigning twitter ID and Twitter Username into the function and getting back the results.

Honestly this is one of my social network tools that I am developing, its not only an example, an idea or a test for PHP functions but you really did on my real web project, I think I should stop working which I am doing now on this tool because you have done it and faster than me.

Just a few quick questions

Can I use it and integrate into my social network tool list?
or everyone on the forum can use your codes for their site?
Can I develop it according to my way?
 

kevinhng86

Member
Registered
Joined
Jan 12, 2017
Messages
58
Points
0
kevinhng86
Thank you FerdieQO for your comment. There is no problem with using the code, everyone can use it for free modify it in anyway or integrate it into anything for any purpose. The code is just a framework. Sorry I couldn't do better than that for now. In my opinion if you play around with this framework and modify it you can probably get it to do every function that twitter API allow you to do.
 

FerdieQO

Well-known member
Joined
Jul 15, 2016
Messages
213
Points
28
Thank you FerdieQO for your comment. There is no problem with using the code, everyone can use it for free modify it in anyway or integrate it into anything for any purpose. The code is just a framework. Sorry I couldn't do better than that for now. In my opinion if you play around with this framework and modify it you can probably get it to do every function that twitter API allow you to do.
Thank you Kevinhng86 I will play any things around your codes, though it is really helpful and easily integrate into a website for users to convert Twtiter id to username or vice versa.

Do you know why I can not run these lines to get the results at a time

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

$Param1 = nameOrIdParam("190405401"); //replace webdothosting with you desire twitter username or ID.
$Result1 = faiTwitGateway("GET", "https://api.twitter.com/1.1/users/show.json", $Params1);
 

kevinhng86

Member
Registered
Joined
Jan 12, 2017
Messages
58
Points
0
kevinhng86
Hi FerdiQO, thank you for pointing that out. It is just sometimes when I write a large function I get confuse and think that I'm on the global level although I nested into other function already. Thus I was declaring class within a function. This is incompatible with PHP because once a class is declare you can't declare it's again. By calling a function again violate PHP policy because all the class within the function have to be re-declare if it is call again. Which in the circumstance of PHP you can't re-declare a class.

Earlier the code can only execute once it will throw error if you call the function. Now you can call the function at many times at you like. The naming context did change a bit.
 
Older Threads
Replies
9
Views
3,144
Replies
2
Views
3,380
Replies
8
Views
7,149
Newer Threads
Replies
17
Views
4,926
Replies
7
Views
6,176
Replies
4
Views
8,871
Latest Threads

Latest Hosting OffersNew Reviews

Sponsors

Tag Cloud

You are using an out of date browser. It may not display this or other websites correctly.
You should upgrade or use an alternative browser.

Top