【问题标题】:cannot use cookies in cURL PHP不能在 cURL PHP 中使用 cookie
【发布时间】:2011-04-20 15:30:33
【问题描述】:

我正在使用 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 查看器查看浏览器 cookie 中的 PHPSESSID。然后我用它来创建一个 cookie 文件供 cURL 读取。然后我可以通过网络服务器的会话检查来查看文件 showbooks.php 。

【问题讨论】:

    标签: php curl session-cookies


    【解决方案1】:

    我使用这段代码 sn-p 从服务器的响应中提取 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 & CURLOPT_COOKIEJAR。为了让生活更轻松 使用 realpath("file.txt") 函数 获取绝对路径。

    【讨论】:

    • 谢谢,您的解决方案对我帮助很大。我不知道为什么网上有些教程没有评论这个问题。
    【解决方案2】:

    文件是可写的吗?它甚至存在吗?

    【讨论】:

    • 文件不存在。但如果它存在,它也不会写入任何 cookie 数据。
    【解决方案3】:

    尝试创建文件并赋予它全局读写权限。

    还可以尝试使用相对路径(例如 ./cookies.txt)而不是 cookie jar 文件的绝对路径。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-02-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-09
      • 1970-01-01
      • 2014-09-12
      • 2012-02-01
      相关资源
      最近更新 更多