How to Send Cookies Using PHP Curl in Addition to Curlopt_Cookiefile

How can I send cookies using PHP curl in addition to CURLOPT_COOKIEFILE?

If the cookie is generated from script, then you can send the cookie manually along with the cookie from the file(using cookie-file option). For example:

# sending manually set cookie
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Cookie: test=cookie"));

# sending cookies from file
curl_setopt($ch, CURLOPT_COOKIEFILE, $ckfile);

In this case curl will send your defined cookie along with the cookies from the file.

If the cookie is generated through javascrript, then you have to trace it out how its generated and then you can send it using the above method(through http-header).

The utma utmc, utmz are seen when cookies are sent from Mozilla. You shouldn't bet worry about these things anymore.

Finally, the way you are doing is alright. Just make sure you are using absolute path for the file names(i.e. /var/dir/cookie.txt) instead of relative one.

Always enable the verbose mode when working with curl. It will help you a lot on tracing the requests. Also it will save lot of your times.

curl_setopt($ch, CURLOPT_VERBOSE, true);

PHP & cURL to use existing COOKIEFILE + Adding my own value to save

Cookies you add manually using CURLOPT_COOKIE won't get saved to the cookie jar at the end of the request.

The only case in which it would is if the server sent back a Set-Cookie header for the cookie you sent in order to update it.

The reason is because cURL requests have a cookie structure that holds cookies which gets written at the end of the request. Data only gets in this structure by a) being read from the cookie file in the first place or b) Set-Cookie headers in the response headers.

With a little care you can append your own cookie to that file with something like this:

$domain = '.go.com';
$expire = time() + 3600;
$name = 'fruit';
$value = 'apple';
file_put_contents($cookieJar, "\n$domain\tTRUE\t/\tFALSE\t$expire\t$name\t$value", FILE_APPEND);

How do I save cookies from a response to a cURL request using php?

Thanks everyone for all the help. However, the problem was something else entirely. I probably should have mentioned that I am working on a Windows server and cURL was unable to read the path to cookie.txt.

Using:

curl_setopt($ch, CURLOPT_COOKIEJAR, dirname(__FILE__) . '/cookie.txt');

instead of:

curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie.txt');

solved the problem.



Related Topics



Leave a reply



Submit