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

标签 php session curl

我正在尝试连接到 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/

相关文章:

php - 如何从本地主机发送smtp邮件

ruby-on-rails - 将用户 ID 添加到 Rails 中的所有日志消息

java - JAXWS 和 session

c# - 在不刷新的情况下在 Page_Unload 上更新 session 值?

python - Nginx WebSocket 代理不断获取 HTTP 301 重定向

php - Laravel Dusk - 类配置不存在

php - 带点和逗号的正则表达式货币格式

php - 如何使用 PHP 发送 HTML 格式的邮件?

linux - 使用 openssl 1.0.x 构建 curl,ldd 显示对 0.9.8 和 1.0.x 的依赖

php - 为 curl 请求选择传出 IP