PHP – Verifying Twitter Credentials using fsock
For all of my Twitter web applications, I have had to verify that the provided login details for a Twitter account are valid. I have used this method for The Re-Revtwter Bot, Twitter Train - TwooTwoo and more recently, The Mass Tweet Lottery.
Without being able to validate the credentials, floods of accounts could be added, and the dont even necessarly have to be theirs.
I have provided a simple function in PHP using fsocks, which will work on 99.99% of servers. The current available methods require cURL, which not all servers support. Read the full article for the function and usage!
Provided below is the function to verify.
public function verifyCredentials($username, $password){ $out="GET http://twitter.com/account/verify_credentials.xml HTTP/1.1\r\n" ."Host: twitter.com\r\n" ."Authorization: Basic ".base64_encode ($username.":".$password)."\r\n" ."Content-type: application/x-www-form-urlencoded\r\n" ."Connection: Close\r\n\r\n"; $fp = fsockopen ('twitter.com', 80); fwrite ($fp, $out); $buf = fread($fp, 1024); fclose ($fp); $pos = strpos($buf,'Could not'); if ($pos === false){ return 1; }else{ return 0; } }
It returns 1 if valid, 0 if invalid.
You can do a simple check like this:
$twitterusername = 'Myusername'; $twitterpassword = 'mypass123'; if (verifyCredentials($twitterusername,$twitterpassword) == 0){ echo 'INVALID LOGIN DETAILS!'; }else{ echo 'VALID!'; }
Any questions/problems? Just ask.




Reader Comments
Great! Thank you so much!