PHP using CURL: is there a way to emulate a cookie instead of saving it to a file?

前端 未结 3 567
情歌与酒
情歌与酒 2020-12-31 06:44

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         


        
相关标签:
3条回答
  • 2020-12-31 06:54

    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.

    0 讨论(0)
  • 2020-12-31 06:55

    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.

    0 讨论(0)
  • 2020-12-31 07:17

    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");
    
    0 讨论(0)
提交回复
热议问题