gpt4 book ai didi

php - 使用 Curl 和 PHP 保持 session 活跃

转载 作者:IT王子 更新时间:2023-10-28 23:55:42 28 4
gpt4 key购买 nike

我正在尝试连接到 API,对用户进行身份验证,然后查看用户详细信息。这是通过首先访问登录端点来完成的

http://api.example.com/login/<username>/<password>

登录然后查看用户详细信息:

http://api.example.com/user/

这一切都适用于网络浏览器。但是,一旦我尝试使用 Curl,登录就可以正常工作,但是在尝试查看用户详细信息时,我会返回 401,未经授权的错误。我相信这是因为 Curl 没有正确保存 session cookie?有人可以指出为什么它不起作用以及如何解决它吗?我试过搜索堆栈交换,但是,我尝试过的解决方案都不适用于我的情况。我用来 curl 端点的代码如下所示。谢谢!

define("COOKIE_FILE", "cookie.txt");

// Login the user
$ch = curl_init('http://api.example.com/login/joe/smith');
curl_setopt ($ch, CURLOPT_COOKIEJAR, COOKIE_FILE);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
echo curl_exec ($ch);

// Read the session saved in the cookie file
echo "<br/><br/>";
$file = fopen("cookie.txt", 'r');
echo fread($file, 100000000);
echo "<br/><br/>";

// Get the users details
$ch = curl_init('http://api.example.com/user');
curl_setopt ($ch, CURLOPT_COOKIEJAR, COOKIE_FILE);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
echo curl_exec ($ch);

这段代码会输出:

HTTP/1.1 200 OK Date: Mon, 22 Oct 2012 21:23:57 GMT Server: LiteSpeed Connection: close X-Powered-By: PHP/5.3.14 Set-Cookie: cfapi=f481129c9616b8f69cc36afe16466545; path=/ Expires: Thu, 19 Nov 1981 08:52:00 GMT Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0 Pragma: no-cache Content-Type: application/json X-Powered-By: CFWAPI 0.1a Content-Length: 46 {"status":200,"msg":"Successfully Logged In."}

# Netscape HTTP Cookie File # http://curl.haxx.se/rfc/cookie_spec.html # This file was generated by libcurl! Edit at your own risk. api.example.com FALSE / FALSE 0 cfapi 94f63b07ccf7e34358c1c922341c020f

HTTP/1.1 401 Unauthorized Date: Mon, 22 Oct 2012 21:23:57 GMT Server: LiteSpeed Connection: close X-Powered-By: PHP/5.3.14 Set-Cookie: cfapi=a8eb015a7c423dde95aa01579c4729a4; path=/ Expires: Thu, 19 Nov 1981 08:52:00 GMT Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0 Pragma: no-cache Content-Type: application/json X-Powered-By: CFWAPI 0.1a Content-Length: 49 {"status":401, "msg":"You need to login first!"}

最佳答案

您还需要设置选项 CURLOPT_COOKIEFILE

手册中这样描述

The name of the file containing the cookie data. The cookie file can be in Netscape format, or just plain HTTP-style headers dumped into a file. If the name is an empty string, no cookies are loaded, but cookie handling is still enabled.

由于您使用的是 cookie jar,因此您最终会在请求完成时保存 cookie,但由于未提供 CURLOPT_COOKIEFILE,因此 cURL 不会在后续请求中发送任何已保存的 cookie。

关于php - 使用 Curl 和 PHP 保持 session 活跃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13020404/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com