且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用C ++ cURL(libcurl)管理简单的PHP会话

更新时间:2022-05-27 22:22:29

据我所知,CURL将自动为您处理会话cookie,只要您重新使用您的CURL句柄为每个请求会话:

As far as I understand it, CURL will handle session cookies automatically for you if you enable cookies, as long as you reuse your CURL handle for each request in the session:

CURL *Handle = curl_easy_init();

// Read cookies from a previous session, as stored in MyCookieFileName.
curl_easy_setopt( Handle, CURLOPT_COOKIEFILE, MyCookieFileName );
// Save cookies from *this* session in MyCookieFileName
curl_easy_setopt( Handle, CURLOPT_COOKIEJAR, MyCookieFileName );

curl_easy_setopt( Handle, CURLOPT_URL, MyLoginPageUrl );
assert( curl_easy_perform( Handle ) == CURLE_OK );

curl_easy_setopt( Handle, CURLOPT_URL, MyActionPageUrl );
assert( curl_easy_perform( Handle ) == CURLE_OK );

// The cookies are actually saved here.
curl_easy_cleanup( Handle );

我不肯定你需要同时设置COOKIEFILE和COOKIEJAR,那样。在任何情况下,您必须设置其中之一,以便在CURL中启用所有的Cookie。您可以执行以下简单的操作:

I'm not positive that you need to set both COOKIEFILE and COOKIEJAR, but the documentation makes it seem that way. In any case, you have to set one of the two in order to enable cookies at all in CURL. You can do something as simple as:

curl_easy_setopt( Handle, CURLOPT_COOKIEFILE, "" );

这将不会从磁盘读取任何Cookie,但会启用会话Cookie卷曲柄。

That won't read any cookies from disk, but it will enable session cookies for the duration of the curl handle.