PHP: 我需要在这个 cURL 脚本中使用 cookies 吗?

PHP: Do I need to use cookies in this cURL script?

以下脚本:

<?php
$sDataFile = '<path>\journal-issue-ToC.htm';
$sURL = 'https://onlinelibrary.wiley.com/toc/14678624/2014/85/1';
$bHeader = false;
$sCAinfo = '<path>\cacert.pem';

$cURLhandle = curl_init();
$FilePointer = fopen($sDataFile, 'wb');

curl_setopt($cURLhandle, CURLOPT_URL, $sURL);
curl_setopt($cURLhandle, CURLOPT_FILE, $FilePointer);
curl_setopt($cURLhandle, CURLOPT_HEADER, $bHeader);
curl_setopt($cURLhandle, CURLOPT_CAINFO, $sCAinfo);

curl_exec($cURLhandle);

curl_close($cURLhandle);
fclose($FilePointer);

保存文件 "journal-issue-ToC.htm" 仅包含以下一行:

The URL has moved <a href="https://onlinelibrary.wiley.com/toc/14678624/2014/85/1?cookieSet=1">here</a>

如果我在浏览器中打开此文件,它会显示 "The URL has moved here",其中单词 "here" linked 到所需的 URL 后缀为“?cookieSet= 1”。如果我单击那个 link,它会将我带到我试图用 cURL.

保存的页面

我想也许我可以通过在 URL 后缀“?cookieSet=1”并再次调用 cURL_exec() 来模拟点击 link。所以我在脚本中添加了三行来做到这一点:

<?php
$sDataFile = '<path>\journal-issue-ToC-2.htm';
$sURL = 'https://onlinelibrary.wiley.com/toc/14678624/2014/85/1';
$bHeader = false;
$sCAinfo = '<path>\cacert.pem';

$cURLhandle = curl_init();
$FilePointer = fopen($sDataFile, 'wb');

curl_setopt($cURLhandle, CURLOPT_URL, $sURL);
curl_setopt($cURLhandle, CURLOPT_FILE, $FilePointer);
curl_setopt($cURLhandle, CURLOPT_HEADER, $bHeader);
curl_setopt($cURLhandle, CURLOPT_CAINFO, $sCAinfo);

curl_exec($cURLhandle);

$sURL .= '?cookieSet=1';
curl_setopt($cURLhandle, CURLOPT_URL, $sURL);
curl_exec($cURLhandle);

curl_close($cURLhandle);
fclose($FilePointer);

此脚本保存文件 "journal-issue-ToC-2.htm" 仅包含以下两行:

The URL has moved <a href="https://onlinelibrary.wiley.com/toc/14678624/2014/85/1?cookieSet=1">here</a>
The URL has moved <a href="http://onlinelibrary.wiley.com/action/cookieAbsent">here</a>

如果我在浏览器中打开这个文件,它会说 "The URL has moved here" 两次,第一个词 "here" linked 到所需的 URL 后缀和以前一样第二个词 "here" linked 到无用页面“http://onlinelibrary.wiley.com/action/cookieAbsent”。

我用谷歌搜索 php curl "The URL has moved here"。大多数结果都是外语的,none 给出了这种行为的原因或如何克服它以实际检索所需页面的任何提示。

我想知道问题是不是我需要在 curl_setopt() 中对 cookie 做些什么。我以前没有使用过 cookie,我一直在阅读 curl_setopt() 中关于它们的选项,感觉有点迷茫。谁能解释一下这些脚本中发生了什么以及我需要更改哪些内容才能使脚本正常工作?

我是 运行 PHP IIS 7.5 上的 Windows 7 64 位下的 7.2.2。

Do I need to use cookies in this cURL script?


您必须将 curl 设置为 store/update 网站收到的 cookie,并在每次请求时发回它们。

此外,由于网站仅在 cookie 被发回时才会提供内容,因此您必须发出两个请求。第一个只会让 cookie 被获取和存储。第二个(将发回存储的 cookie)将获取实际内容。

为了存储收到的 cookie 并在每次请求时发送它们,您需要这些行:

curl_setopt($cURLhandle, CURLOPT_COOKIEFILE, "path_to\cookies.txt");
curl_setopt($cURLhandle, CURLOPT_COOKIEJAR,  "path_to\cookies.txt");

path_to\cookies.txt 是本地存储 cookie 的文件的绝对路径。 该文件是在第一次调用时创建的。当然目标目录必须是readable/writeable.

最后进行两次 curl 调用:

1) 只需加载主页https://onlinelibrary.wiley.com/

2) 加载所需页面https://onlinelibrary.wiley.com/toc/14678624/2014/85/1


请注意,如果您要获取多个页面,则只需在第一次执行 1 步。