1

我需要使用网站作为登录用户。下面的代码很好地完成了这项工作,但是每次调用脚本时都必须登录。我只想登录一次,然后使用会话 cookie。

$c=curl_init();
$url='http://www.site.com/login/';              
$opt=array(CURLOPT_URL=>$url,CURLOPT_COOKIEJAR=>'cookie.txt',CURLOPT_POST=>1,CURLOPT_RETURNTRANSFER=>1,CURLOPT_POSTFIELDS=>'username=usr123&password=pass&submit='); //submit=1 works too
curl_setopt_array($c,$opt);
curl_exec($c);
$url='http://www.site.com/next';
$opt2=array(CURLOPT_URL=>$url,CURLOPT_RETURNTRANSFER=>1);
curl_setopt_array($c,$opt2);
$out=curl_exec($c);
echo $out;
curl_close($c);

我尝试使用会话,但由于某种原因,用户登录不起作用。

$c=curl_init();
$ag='Mozilla/5.0 (Windows; U; Windows NT 5.1; ru; rv:1.9.0.7) Gecko/2009021910 Firefox/3.0.7 (.NET CLR 3.5.30729)';
if(!file_exists('cookie.txt')){
  $url='http://www.site.com/login/';
  $opt=array(CURLOPT_URL=>$url,
  CURLOPT_COOKIEJAR=>'cookie.txt',
  CURLOPT_COOKIEFILE=>'cookie.txt',
  CURLOPT_POST=>0,
  CURLOPT_RETURNTRANSFER=>1,
  CURLOPT_FOLLOWLOCATION=>1,
  CURLOPT_USERPWD=>'usr123:pass,
  CURLOPT_SSL_VERIFYPEER=>false,
  CURLOPT_SSL_VERIFYHOST=>0,
  CURLOPT_USERAGENT=>$ag);
  curl_setopt_array($c,$opt);
  curl_exec($c);
}  

$url='http://www.site.com/next/';
$opt2=array(CURLOPT_URL=>$url,
CURLOPT_COOKIEJAR=>'cookie.txt',
CURLOPT_COOKIEFILE=>'cookie.txt',
CURLOPT_RETURNTRANSFER=>1,
CURLOPT_FOLLOWLOCATION=>1,
CURLOPT_SSL_VERIFYPEER=>false,
CURLOPT_SSL_VERIFYHOST=>2,
CURLOPT_USERAGENT=>$ag);
curl_setopt_array($c,$opt2);
$out=curl_exec($c);
echo $out;
curl_close($c);
4

1 回答 1

1

解决方案:

if(!file_exists('cookie.txt')){
  $url='http://www.site.com/login/';                         

  $opt=array(CURLOPT_URL=>$url,CURLOPT_COOKIEJAR=>'cookie.txt',CURLOPT_POST=>1,
       CURLOPT_RETURNTRANSFER=>1,CURLOPT_POSTFIELDS=>'username=usr123&password=pass&submit=');
  curl_setopt_array($c,$opt);
  curl_exec($c);
}
$url='http://www.site.com/next';
$opt2=array(CURLOPT_URL=>$url,CURLOPT_COOKIEJAR=>'cookie.txt',CURLOPT_COOKIEFILE=>'cookie.txt',
      CURLOPT_POST=>0,CURLOPT_RETURNTRANSFER=>1,CURLOPT_USERPWD=>'usr123:pass');
curl_setopt_array($c,$opt2);
$output=curl_exec($c);
echo $output;
于 2014-03-08T01:32:34.857 回答