使用Php和Curl无法登录到远程服务器

时间:2014-05-06 14:10:11

标签: php cookies curl

尝试使用curl和php登录远程服务器但是没有启用cookie的错误。这是我的代码:

error_reporting(E_ALL);
ini_set("display_errors", 1);
$url = 'http://uk.songselect.com/account/login/';
$username = '*****';
$password = '******';
$ch = curl_init($url); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_COOKIESESSION, true);
curl_setopt($ch, CURLOPT_COOKIEJAR, 'tmp/cookie.txt');
curl_setopt($ch, CURLOPT_COOKIEFILE, 'tmp/cookie.txt');


//run the process and fetch the document
$doc = curl_exec($ch);



// extract __RequestVerificationToken input field
preg_match('#<input name="__RequestVerificationToken" type="hidden" value="(.*?)"#is',            $doc, $match);

 $token = $match[1];



// ENABLE HTTP POST
curl_setopt ($ch, CURLOPT_POST, 1);

// SET POST PARAMETERS : FORM VALUES FOR EACH FIELD
curl_setopt ($ch, CURLOPT_POSTFIELDS,         '__RequestVerificationToken='.$token.'&UserName='.$username.'&Password='.$password.'');

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);



//run the process and fetch the document
$doc = curl_exec($ch);
echo $doc;

//terminate curl process
curl_close($ch);

//print output


echo $token;

这是我得到的错误:&#39;您需要在浏览器中启用Cookie才能将SongSelect网站用作经过身份验证的用户。&#39;

为什么会发生这种情况?

谢谢!

2 个答案:

答案 0 :(得分:1)

我猜你需要初始化另一个cUrl频道,其中包含保存在tmp / cookie.txt中的cookie并执行它。

答案 1 :(得分:0)

要为您的curl请求添加Cookie:

curl_setopt( $ch, CURLOPT_COOKIESESSION, true );
curl_setopt( $ch, CURLOPT_COOKIEJAR, uniquefilename );
curl_setopt( $ch, CURLOPT_COOKIEFILE, uniquefilename );