我使用此代码登录我的帐户。 http://www.mywebsite.com/login.php' ;;
$postVars = 'username=myuser&password=1234';
$tmpfname = 'cookie.txt';
$page = '/login.php';
$headers = array(
"POST ".$page." HTTP/1.1",
"Content-Type: application/x-www-form-urlencoded; charset=UTF-8",
"Accept: */*",
"Accept-Language: en-US,en;q=0.5",
"Cache-Control: no-cache",
"Referer: http://www.mywebsite.com/",
"Content-length: ".strlen($postVars),
"Pragma: no-cache",
"Connection: keep-alive",
"X-Requested-With: XMLHttpRequest",
"Cache-Control: no-cache"
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.0');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postVars);
curl_setopt($ch, CURLOPT_COOKIEJAR, $tmpfname);
curl_setopt($ch, CURLOPT_COOKIEFILE, $tmpfname);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
$run = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
?>
登录后,我想访问http://mywebsite.com/profile.php
访问http://example.com/home.php,and和http://mywebsite.com/logout.php退出我该怎么办?你有一个例子吗?
答案 0 :(得分:2)
我想你想在CURL中维护一个会话(就像浏览器一样)。这样您就可以访问激活访问控制的其他页面。
为此,您可以做的是,在登录时将cookie保存在文件中。并在访问其他页面时使用该cookie。因为通常会话是通过cookie维护的。
如果您使用CURLOPT_COOKIE_FILE和CURLOPT_COOKIE_JAR,那么curl将从/向文件读取/写入cookie。
所以将这3行添加到所有curl查询中。
$ckfile = tempnam ("/tmp", 'cookiename');
curl_setopt ($ch, CURLOPT_COOKIEJAR, $ckfile);
curl_setopt ($ch, CURLOPT_COOKIEFILE, $ckfile);