How to send cookies with file_get_contents

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. 🙂

Leave a Comment