Twitter使用cURL登录

时间:2014-01-24 12:58:43

标签: php curl twitter

所以我有这个脚本利用cURL登录twitter。但问题是,虽然脚本确实有效,但它只会创建一个临时会话,并且用户不会保持登录状态。我将如何修改它以确保用户确实保持登录状态?

 # 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_COOKIEJAR, "/tmp/cookie.txt");
 curl_setopt($ch, CURLOPT_REFERER, "https://twitter.com/");
 $html = curl_exec($ch);

 # parse authenticity_token out of html response
 preg_match('/<input type="hidden" value="([a-zA-Z0-9]*)" name="authenticity_token"\/>/', $html, $match);
 $authenticity_token = $match[1];

 $username = "username";
 $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 response
 curl_exec($ch);
 curl_close($ch);

2 个答案:

答案 0 :(得分:0)

我会尝试添加:

curl_setopt($ch, CURLOPT_COOKIESESSION, TRUE);
curl_setopt($ch, CURLOPT_COOKIEJAR, "/tmp/cookie.txt");

答案 1 :(得分:0)

还可以使用cookie-jar选项。

curl_setopt($ch, CURLOPT_COOKIEJAR, "/tmp/cookie.txt");

基本上使用CURLOPT_COOKIEFILE选项curl用于在发送请求期间从文件加载cookie。使用CURLOPT_COOKIEJAR选项,curl用于将cookie保存(从响应中)到定义的文件中。