Web Hosting Forum Login
Not a member yet? Sign up

PHP - Convert Twitter Id to Username or Vice Versa

  • FORUMS
  • WEB DESIGN
  • WEB HOSTING OFFERS
  • ADVERTISING
  • WEB HOSTING
  • REQUEST A HOST
  • BEST WEB HOSTING
  • QUICK MENU
  • REGISTER HERE - Join us for FREE
Results 1 to 5 of 5
  1. #1
    Join Date
    Jan 2017
    Posts
    58
    Thanks
    16
    Thanked 20 Times in 14 Posts
    Thumbs Up/Down
    Received: 45/0
    Given: 39/0

    PHP - Convert Twitter Id to Username or Vice Versa

    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 by kevinhng86; 01-19-2017 at 03:23 AM.

  2. The Following 5 Users Say Thank You to kevinhng86 For This Useful Post:
    Chris Worner (01-14-2017),Dr. McKay (01-14-2017),FerdieQO (01-14-2017),LJSHost (01-13-2017),mattnz (01-14-2017)

  3. #2
    Join Date
    Jul 2016
    Posts
    123
    Thanks
    42
    Thanked 11 Times in 8 Posts
    Thumbs Up/Down
    Received: 28/0
    Given: 132/0
    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.

    Name:  twitter-id-to-username.png
Views: 73
Size:  14.1 KB

    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?

  4. #3
    Join Date
    Jan 2017
    Posts
    58
    Thanks
    16
    Thanked 20 Times in 14 Posts
    Thumbs Up/Down
    Received: 45/0
    Given: 39/0
    Quote Originally Posted by FerdieQO View Post
    Cool kevinhng86! I am trying to test it and will give you feedback when I can see results from your codes. 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?
    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.

  5. #4
    Join Date
    Jul 2016
    Posts
    123
    Thanks
    42
    Thanked 11 Times in 8 Posts
    Thumbs Up/Down
    Received: 28/0
    Given: 132/0
    Quote Originally Posted by kevinhng86 View Post
    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);

  6. #5
    Join Date
    Jan 2017
    Posts
    58
    Thanks
    16
    Thanked 20 Times in 14 Posts
    Thumbs Up/Down
    Received: 45/0
    Given: 39/0
    Quote Originally Posted by FerdieQO View Post
    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
    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.

Newer Threads

  1. cPanelHosting
    cPanelHosting
    Replies: 0 | Views: 297
    Last post by cPanelHosting, 01-14-2017, 03:29 AM
  2. eva2000
    CaygriWEB
    Replies: 17 | Views: 1163
    Last post by CaygriWEB, 07-20-2017, 08:41 AM
  3. Chris Worner
    eva2000
    Replies: 2 | Views: 1033
    Last post by eva2000, 01-15-2017, 12:07 AM
  4. Maxoq
    eva2000
    Replies: 7 | Views: 1184
    Last post by eva2000, 01-18-2017, 06:28 PM
  5. TheCompWiz
    Exim or Dovecot
    By TheCompWiz in forum Web Hosting
    HostYourNet-DR
    Replies: 4 | Views: 1056
    Last post by HostYourNet-DR, 01-17-2017, 10:09 AM

Older Threads

  1. Polymath
    New Member
    By Polymath in forum New Member Introductions
    Polymath
    Replies: 9 | Views: 910
    Last post by Polymath, 01-14-2017, 09:33 AM
  2. energizedit
    archhosting
    Replies: 10 | Views: 1592
    Last post by archhosting, 02-05-2017, 09:05 AM
  3. steitieh
    VirtuBox
    Replies: 2 | Views: 809
    Last post by VirtuBox, 01-12-2017, 11:00 PM
  4. Chris Worner
    rad-jason
    Replies: 11 | Views: 1215
    Last post by rad-jason, 06-23-2017, 09:32 PM
  5. FerdieQO
    kevinhng86
    Replies: 8 | Views: 820
    Last post by kevinhng86, 01-13-2017, 05:49 PM

Latest Threads

  1. David Beroff
    VirtuBox
    Replies: 1 | Views: 18
    Last post by VirtuBox, Today, 03:37 AM
  2. exa-edward
    exa-edward
    Replies: 4 | Views: 113
    Last post by exa-edward, Today, 09:55 AM
  3. JFSG
    JFSG
    Replies: 0 | Views: 27
    Last post by JFSG, Yesterday, 07:43 PM
  4. UltratechHost
    UltratechHost
    Replies: 0 | Views: 15
    Last post by UltratechHost, Yesterday, 04:31 PM
  5. macklong
    macklong
    Replies: 0 | Views: 21
    Last post by macklong, Yesterday, 01:10 AM

Similar Threads

  1. FerdieQO
    kevinhng86
    Replies: 8 | Views: 820
    Last post by kevinhng86, 01-13-2017, 05:49 PM
  2. jmlopez
    Luxin Host
    Replies: 5 | Views: 771
    Last post by Luxin Host, 07-11-2016, 08:25 PM
  3. Epic
    HostNurse
    Replies: 2 | Views: 1001
    Last post by HostNurse, 02-21-2015, 08:59 AM
  4. freds86
    dandeedo
    Replies: 2 | Views: 883
    Last post by dandeedo, 11-19-2014, 02:12 PM
  5. zetar060115
    Bulan
    Replies: 2 | Views: 1294
    Last post by Bulan, 09-23-2013, 07:11 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  

Web Hosting Forum

ForumWeb.Hosting is a web hosting forum where you’ll find in-depth discussions and resources to help you find the best hosting providers for your websites or how to manage your hosting whether you are new or experienced. You’ll find it all here. With topics ranging from web hosting, internet marketing, search engine optimization, social networking, make money online, affiliate marketing as well as hands-on technical support for web design, programming and more. We are a growing community of like-minded people that is keen to help and support each other with ambitions and online endeavors. Learn and grow, make friends and contacts for life.

Community

The world's smartest hosting providers come here to discuss & share what's trending in the web hosting world!
Copyright ©2017, ForumWeb.Hosting. All rights reserved. Web Hosting Forum for webmasters, web hosting providers, designers and web developers.

Welcome to Forum Web Hosting

The World's Number 1 Web Hosting Community, Reviews & Services

Log in!

Continue with Facebook
Continue With Email. By signing up you indicate that you have read and agree to the Terms of Service and Privacy Policy.

Sign in Manually

Need an account? Sign up now!