使用 Curl 和 PHP 保持会话活动状态

2022-08-30 09:53:02

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

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

以登录,然后执行以下操作以查看用户详细信息:

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

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

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!"}

答案 1

您还需要设置选项 。CURLOPT_COOKIEFILE

该手册将其描述为

包含 Cookie 数据的文件的名称。Cookie文件可以是Netscape格式,也可以只是将普通的HTTP样式标头转储到文件中。如果名称为空字符串,则不会加载任何 Cookie,但仍会启用 Cookie 处理。

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


答案 2

您已经正确使用了“CURLOPT_COOKIEJAR”(写作),但还需要设置“CURLOPT_COOKIEFILE”(阅读)

curl_setopt ($ch, CURLOPT_COOKIEJAR, COOKIE_FILE); 
curl_setopt ($ch, CURLOPT_COOKIEFILE, COOKIE_FILE); 

推荐