保存远程网页的cookie

9 php cookies curl

我有一个PHP应用程序需要从另一个网页抓取内容,而我正在阅读的网页需要一个cookie.

我找到了有关如何使用cookie(http://groups.google.com/group/comp.lang.php/msg/4f618114ab15ae2a)进行此调用的信息,但是我不知道如何生成cookie,或者cookie的保存方式/位置.

例如,要通过wget阅读此网页,请执行以下操作:

wget --quiet --save-cookies cookie.file --output-document=who.cares \ 
  http://remoteServer/login.php?user=xxx&pass=yyy

wget --quiet --load-cookies cookie.file --output-document=documentiwant.html \
  http://remoteServer/pageicareabout.html
Run Code Online (Sandbox Code Playgroud)

...我的问题是如何在PHP中执行'--save-cookies'位,以便我可以在后续PHP stream_context_create/file_get_contents块中使用cookie:

$opts = array(http'=> array(
  'method'=> "GET",
  'header'=>
    "Accept-language: en\r\n" .
    "Cookie: **NoClueAtAll**\r\n"
  )
);

$context = stream_context_create($opts);
$documentiwant = file_get_contents("http://remoteServer/pageicareabout.html",
  0, $context);
Run Code Online (Sandbox Code Playgroud)

小智 14

Shazam - 有效!太多了!万一其他人偶然发现这个页面,这里需要详细说明:

  1. 安装cURL(对我而言,就像在ubuntu中'sudo apt-get install php5-curl'一样简单)
  2. 将之前列出的PHP更改为以下内容:

    <?php
    
    $cr = curl_init('http://remoteServer/login.php?user=xxx&pass=yyy');
    curl_setopt($cr, CURLOPT_RETURNTRANSFER, true); 
    curl_setopt($cr, CURLOPT_COOKIEJAR, 'cookie.txt');   
    $whoCares = curl_exec($cr); 
    curl_close($cr); 
    
    $cr = curl_init('http://remoteServer/pageicareabout.html');
    curl_setopt($cr, CURLOPT_RETURNTRANSFER, true); 
    curl_setopt($cr, CURLOPT_COOKIEFILE, 'cookie.txt'); 
    $documentiwant = curl_exec($cr);
    curl_close($cr);
    
    ?>
    
    Run Code Online (Sandbox Code Playgroud)

以上代码段受http://www.weberdev.com/get_example-4555.html的影响很大.


Gre*_*reg 5

使用cURL可能会更好.使用curl_setopt设置cookie处理选项.

如果这只是一次性的事情,你可以使用Firefox和Live HTTP Headers来获取标题,然后将其粘贴到PHP代码中.