简体   繁体   中英

Is it possible to set the cookie content with CURL?

I have been searching for a way, to specify the cookie data for CURL. I have found some solutions on how to save the cookies from a visited page, but that's not what I need. What I want is, to write the data for the cookie myself, so CURL uses it.

You can use curl_setopt with the CURLOPT_COOKIE constant:

<?php
// create a new cURL resource
$ch = curl_init();

// cookies to be sent
curl_setopt($ch, CURLOPT_COOKIE, "fruit=apple; colour=red");

You really should read the documentation - it's listed with exactly the keywords you'd expect and contains a lot of helpful info:

-b, --cookie

(HTTP) Pass the data to the HTTP server as a cookie. It is supposedly the data previously received from the server in a "Set-Cookie:" line. The data should be in the format "NAME1=VALUE1; NAME2=VALUE2".

If no '=' symbol is used in the line, it is treated as a filename to use to read previously stored cookie lines from, which should be used in this session if they match. Using this method also activates the "cookie parser" which will make curl record incoming cookies too, which may be handy if you're using this in combination with the -L, --location option. The file format of the file to read cookies from should be plain HTTP headers or the Netscape/Mozilla cookie file format.

NOTE that the file specified with -b, --cookie is only used as input. No cookies will be stored in the file. To store cookies, use the -c, --cookie-jar option or you could even save the HTTP headers to a file using -D, --dump-header!

If this option is set more than once, the last one will be the one that's used.

cURL can use a cookie file in Netscape format . Just create such a file yourself and use as the CURLOPT_COOKIEFILE option.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM