tags:

views:

2593

answers:

2

Hiya - I've got a PHP application which needs to grab the contents from another web page, and the web page I'm reading needs a cookie.

I've found info on how to make this call once i have the cookie ( http://groups.google.com/group/comp.lang.php/msg/4f618114ab15ae2a ), however I've no idea how to generate the cookie, or how / where the cookie is saved.

For example, to read this web page via wget I do the following:

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

... my question is how do I do the '--save-cookies' bit in PHP so that I can use the cookie in the follow-up PHP stream_context_create / file_get_contents block:

$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);
+2  A: 

You'd probably be better off using cURL. Use curl_setopt to set up the cookie handling options.

If this is just a one-off thing, you could use Firefox with Live HTTP Headers to get the header, then paste it into your PHP code.

Greg
+1  A: 

Shazam - that worked ! Thx soooo much ! In case someone else stumbles upon this page, here's what was needed in detail:

  1. install cURL (for me it'was as simple as 'sudo apt-get install php5-curl' in ubuntu)
  2. change the prior-listed PHP to the following:

.

<?php

$cr = curl_init('http://remoteServer/login.php?user=xxx&amp;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);

?>

... thx very much for the redirect to cURL (above code snippet heavily influenced by http://www.weberdev.com/get_example-4555.html ).

- Dave