logging into twitter with curl logging into twitter with curl curl curl

logging into twitter with curl


The CURLOPT_COOKIESESSION is used to indicate a new session. That's not what you want, since you need to send the session cookie in the second post.

I got the twitter login to work with this code:

<?php# First call gets hidden form field authenticity_token# and session cookie$ch = curl_init();$sTarget = "https://twitter.com/";curl_setopt($ch, CURLOPT_URL, $sTarget);curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);curl_setopt($ch, CURLOPT_COOKIEFILE, "/tmp/cookie.txt");curl_setopt($ch, CURLOPT_REFERER, "https://twitter.com/");$html = curl_exec($ch);# parse authenticity_token out of html responsepreg_match('/<input type="hidden" value="([a-zA-Z0-9]*)" name="authenticity_token"\/>/', $html, $match);$authenticity_token = $match[1];$username = "your@email.com";$password = "password";# set post data$sPost = "session[username_or_email]=$username&session[password]=$password&return_to_ssl=true&scribe_log=&redirect_after_login=%2F&authenticity_token=$authenticity_token";# second call is a post and performs login$sTarget = "https://twitter.com/sessions";curl_setopt($ch, CURLOPT_URL, $sTarget);curl_setopt($ch, CURLOPT_POST, true);curl_setopt($ch, CURLOPT_POSTFIELDS, $sPost);curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-type: application/x-www-form-urlencoded"));# display server responsecurl_exec($ch);curl_close($ch);?>

PS: Sorry for not reading your post properly the first time.


I noticed two things:

1) Try to URL encode your POST data

such as:session%5Busername_or_email%5D=user&session%5Bpassword%5D=password...

instead of:session[username_or_email]=user&session[password]=password...

2) twitter has a hidden field named authenticity_token in the login form. It is bound to the session. Thus you cannot use a static authenticity_token, you have to read the login form first and use the authenticity_token field from there.

Hope that helps.