如何在php的cURL中维护会话?

2022-08-30 19:10:30

我们如何在cURL中维护会话?

我有一个代码发送网站的登录详细信息并成功登录,我需要在网站上维护会话才能继续。

这是我的代码,用于使用cURL登录网站

  <?php  
        $socket = curl_init();
        curl_setopt($socket, CURLOPT_URL, "http://www.XXXXXXX.com");
    curl_setopt($socket, CURLOPT_REFERER, "http://www.XXXXXXX.com");
    curl_setopt($socket, CURLOPT_POST, true);
    curl_setopt($socket, CURLOPT_USERAGENT, $agent);
    curl_setopt($socket, CURLOPT_POSTFIELDS, "form_logusername=XXXXX&form_logpassword=XXXXX");
    curl_setopt($socket, CURLOPT_COOKIESESSION, true);
    curl_setopt($socket, CURLOPT_COOKIEJAR, "cookies.txt");
    curl_setopt($socket, CURLOPT_COOKIEFILE, "cookies.txt");
    $data = curl_exec($socket);
    curl_close($socket); 
   ?>

答案 1

这是我找到的做这个链接的最好方法:

下面的文字是博客文章内容的“重新混合”版本:

 $useragent = $_SERVER['HTTP_USER_AGENT'];
 $strCookie = 'PHPSESSID=' . $_COOKIE['PHPSESSID'] . '; path=/';

session_write_close();

$ch = curl_init();
$ch = curl_init($rssFeedLink); 
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_USERAGENT, $useragent);
curl_setopt( $ch, CURLOPT_COOKIE, $strCookie );

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

有什么作用?它将结束当前会话并存储会话数据。显然,PHP不喜欢多个脚本使用会话,因此,它会锁定它。将session_write_close可确保存储当前会话,以便您可以检索和使用它。session_write_close()

如果您不使用新的会话 ID,则将生成一个新的会话 ID,而不是使用当前的会话 ID。session_write_close()

此外,PHPSESSID 应替换为会话变量的名称。根据OWSAP的重新命令,它应该是更通用的东西,如anId

有时您需要发送一个用户代理和帖子,所以我包含了参数。CURLOPT_USERAGENT


答案 2

这就是你如何对会话进行CURL

//initial request with login data

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://www.example.com/login.php');
curl_setopt($ch, CURLOPT_USERAGENT,'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/32.0.1700.107 Chrome/32.0.1700.107 Safari/537.36');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, "username=XXXXX&password=XXXXX");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_COOKIESESSION, true);
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie-name');  //could be empty, but cause problems on some hosts
curl_setopt($ch, CURLOPT_COOKIEFILE, '/var/www/ip4.x/file/tmp');  //could be empty, but cause problems on some hosts
$answer = curl_exec($ch);
if (curl_error($ch)) {
    echo curl_error($ch);
}

//another request preserving the session

curl_setopt($ch, CURLOPT_URL, 'http://www.example.com/profile');
curl_setopt($ch, CURLOPT_POST, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, "");
$answer = curl_exec($ch);
if (curl_error($ch)) {
    echo curl_error($ch);
}

我在印象页面上看到过这个


推荐