我在用curl解析一个网站。
http://www.hcmiu.edu.vn/bookforsale/showbooks.php
需要会话才能查看,如果没有会话,则页面将重定向到:
http://www.hcmiu.edu.vn/bookforsale/perInfo.php
我使用此代码获取会话cookie,但不知道为什么看不到对文件cookies.txt的任何更改
$urltopost = "http://www.hcmiu.edu.vn/bookforsale/perInfo.php";
$datatopost = array (
"name" => "abc",
"tel" => "99999999",
"email" => "abc@gmail.com",
"profession" => "abc",
"employer" => "abc",
"tel_work" => "99999999",
);
$ch = curl_init($urltopost);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $datatopost);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_COOKIEJAR, "/tmp/cookies.txt");
$returnData = curl_exec($ch);
$file = fopen("example.txt", "w");
fwrite($file, $returnData);
fclose($file);
curl_close($ch);
然而,我明白了:
Set-Cookie: PHPSESSID=1egb993objkrdp3gi5mpvs02g0; path=/
在标题中。谢谢你的帮助
-编辑:
我使用了一种复杂的方法:我使用http查看器查看浏览器cookies中的phpsessid。然后我用它创建一个cookies文件供curl读取。然后我可以通过web服务器的会话检查来查看showbooks.php文件。
最佳答案
我使用此代码片段从服务器的响应中提取cookie:
$returnData = curl_exec($ch);
$cookie = '';
$pattern = '/Set-Cookie:(.*?)\n/';
if (preg_match($pattern, $returnData, $result))
$cookie = $result[1];
我已经描述了我在this post中的经历。这种方法不使用cookie文件。
关于cookie文件,请考虑http://php.net/manual/en/book.curl.php中的以下建议:
使用绝对路径设置
变量curlopt_cookiefile&
库洛普特库基耶尔。让生活更轻松
使用realpath(“file.txt”)函数
得到绝对路径。
关于php - 无法在cURL PHP中使用Cookie,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3852750/