Alex Rivera | Logout

How to send cookies with file_get_contents

Asked 2008-11-20T19:46:48.770
19

I'm trying to get the contents from another file with file_get_contents (don't ask why).
I have two files: test1.php and test2.php. test1.php returns a string, bases on the user that is logged in.

test2.php tries to get the contents of test1.php and is being executed by the browser, thus getting the cookies.

To send the cookies with file_get_contents, I create a streaming context:

$opts = array('http' => array('header'=> 'Cookie: ' . $_SERVER['HTTP_COOKIE']."\r\n"))`;

I'm retrieving the contents with:

$contents = file_get_contents("http://www.example.com/test1.php", false, $opts);

But now I get the error:

Warning: file_get_contents(http://www.example.com/test1.php) [function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found

Does somebody knows what I'm doing wrong here?

edit:
forgot to mention: Without the streaming_context, the page just loads. But without the cookies I don't get the info I need.

Edit
Report

1 Answer

34

First, this is probably just a typo in your question, but the third arguments to file_get_contents() needs to be your streaming context, NOT the array of options. I ran a quick test with something like this, and everything worked as expected

$opts = array('http' => array('header'=> 'Cookie: ' . $_SERVER['HTTP_COOKIE']."\r\n"));
$context = stream_context_create($opts);
$contents = file_get_contents('http://example.com/test1.txt', false, $context);
echo $contents;

The error indicates the server is returning a 404. Try fetching the URL from the machine PHP is running on and not from your workstation/desktop/laptop. It may be that your web server is having trouble reaching the site, your local machine has a cached copy, or some other network screwiness.

Be sure you repeat your exact request when running this test, including the cookie you're sending (command line curl is good for this). It's entirely possible that the page in question may load fine in a browser without the cookie, but when you send the cookie the site actually is returning a 404.

Make sure that $_SERVER['HTTP_COOKIE'] has the raw cookie you think it does.

If you're screen scraping, download Firefox and a copy of the LiveHTTPHeaders extension. Perform all the necessary steps to reach whatever page it is you want in Firefox. Then, using the output from LiveHTTPHeaders, recreate the exact same request requence. Include every header, not just the cookies.

Finally, PHP Curl exists for a reason. If at all possible, (I'm not asking!) use it instead. :)

answered 2008-11-21T06:38:53.133

Your Answer