PHP使用CURL:有没有办法模拟一个cookie,而不是保存到一个文件? [英] PHP using CURL: is there a way to emulate a cookie instead of saving it to a file?

查看:383
本文介绍了PHP使用CURL:有没有办法模拟一个cookie,而不是保存到一个文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我访问使用称为session_id的变量的REST API服务。 API要求将其存储在cookie中,并且我完成此操作如下:

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); //prevent unverified SSL ""

        $contents = curl_exec($ch);
        curl_close($ch);

现在的问题是许多不同的用户被称为许多不同的时间。 (所以许多不同的cookie文件必须保存)我想要一个方法来简单地存储session_id在一个变量,而不是引用cookie文件。到目前为止,我的所有尝试都被服务拒绝。任何人都可以建议方法来存储会话ID和cookie信息,而不保存到文件?注意,读取会话ID没有问题,它以XML返回。由于某种原因,传回它而不引用实际生成的文件不会传递安全凭证。任何更多的信息,为什么这可能是有帮助的。

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.

推荐答案

Cookie是与请求一起发送的简单文本标题。 CURL允许您直接使用 CURLOPT_COOKIE 指定那些。

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');

如果你知道要发送什么信息,你可以这样构造自己的cookie头。 COOKIEJAR / COOKIEFILE选项只是自动解析,保存和发送。如果您不想写入文件,则必须手动进行(读取接收到的Cookie标头,创建要发送的Cookie标头)。

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.

这篇关于PHP使用CURL:有没有办法模拟一个cookie,而不是保存到一个文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆