PHP using CURL: is there a way to emulate a cookie instead of saving it to a file?
I access a REST api service that utilizes a variable called session_id. The API calls for this to be stored in a cookie and I accomplish this as follows:
$ch = curl_init(); // initialize curl handle
curl_setopt($ch, CURLOPT_URL, $url); //set target URL
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);// allow redirects
curl_setopt($ch, CURLOPT_COOKIEFILE, './Cookie.txt');
curl_setopt($ch, CURLOPT_COOKIEJAR, './Cookie.txt');
curl_setopt($ch, CURLOPT_POST, TRUE); // set POST method
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); //set headers
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, TRUE); //return the headers so we can get session id
curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, FALSE); //prevent unverified SSL certificate error
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, FALSE); //preven开发者_开发百科t unverified SSL ""
$contents = curl_exec($ch);
curl_close($ch);
Now the problem is this is called many different times by many different users. (so many different cookie files have to be saved) I'd like a way to simply store the session_id in a variable instead of referencing the cookie file. So far all my attempts are rejected by the service. Can anyone suggest methods to store the session id and cookie information without saving it to a file? Note that reading the session id is no problem, it's returned in XML. For some reason passing it back without referencing the actual generated file does not pass security credentials. Any more information as to why this might be would also be helpful.
Cookies are simple text headers sent along with the request. CURL allows you to specify those directly using CURLOPT_COOKIE
.
curl_setopt($ch, CURLOPT_COOKIE, 'key=value;anotherkey=anothervalue');
If you know what information to send, you can construct your own cookie header this way. The COOKIEJAR/COOKIEFILE options just automate parsing, saving and sending. You'll have to do that manually (read received Cookie headers, create Cookie headers to be send), if you don't want to write to a file.
There is a good example here,
http://sgjoomla.googlecode.com/svn/trunk/joomla/curltest.php
For some reason, the cookie part is commented out but all the code you need is still there.
Basically, you parse the "Set-Cookie" headers yourself and save the cookie value by doing this,
curl_setopt ($ch, CURLOPT_HEADERFUNCTION, 'read_header');
Put the cookie value in a global. In next call, set it like this,
curl_setopt($ch, CURLOPT_COOKIE, "$cookieName=$cookieValue");
I use tempnam to generate a unique file name.
$ckfile = tempnam ("/tmp", "cookieMyWeb");
curl_setopt ($ch, CURLOPT_COOKIEJAR, $ckfile);
Generate a new file name before using curl.
精彩评论