tags:

views:

305

answers:

3

Is it possible to receive the cookies set by the remote server when doing a file_get_contents request?

I need php to do a http request and store the cookies and make a second request.

+7  A: 

you should use cURL for that purpose, cURL implement a feature called the cookie jar which permit to save cookies in a file and reuse them for subsequent request(s).

Here come a quick code snipet how to do it:

/* STEP 1. let’s create a cookie file */
$ckfile = tempnam ("/tmp", "CURLCOOKIE");
/* STEP 2. visit the homepage to set the cookie properly */
$ch = curl_init ("http://somedomain.com/");
curl_setopt ($ch, CURLOPT_COOKIEJAR, $ckfile); 
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec ($ch);

/* STEP 3. visit cookiepage.php */
$ch = curl_init ("http://somedomain.com/cookiepage.php");
curl_setopt ($ch, CURLOPT_COOKIEFILE, $ckfile); 
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec ($ch);

note: has to be noted you should have the pecl extension (or compiled in PHP) installed or you won't have access to the cURL API.

RageZ
Is it possible to just store the cookies in a variable, I was trying to prevent writing them to disk. I really just need to pull out one cookie value.
Louis W
Doesn't look like it. Use http://www.php.net/manual/en/function.tempnam.php to create a temp file and remove it after you're done.
ceejayoz
@Louis: not with curl but anyway it's kind of a few bytes file and you can just `unlink` it after you are done.
RageZ
Reflected in my answer, there are ways to do this (not using CURL) that do not require file storage for cookies.
Tim Lytle
+1  A: 

You can either install and use the PECL extension for HTTP, or make sure your php installation was compiled with the optional curl library.

soulmerge
A: 

I believe you co do it pretty easily with the Zend_Http object. Here is the documentation about adding cookies to a request.

To get the cookies from a request (automatically retrieved I believe), just use getCookieJar() on the Zend_Http object.

That should be easy to implement; however, the php manual has a user comment on how to deal with cookies using the http stream.

Tim Lytle