Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
910 views
in Technique[技术] by (71.8m points)

authentication - cURL login session

I need to use a website as a logged user. The code below does the job well, however it has to log in every time the script is called. I'd like to log in just once and from then on use session cookies.

$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);

I tried using session, but for some reason the user login doesn't work.

$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);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Solution:

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...