如何让Curl使用与PHP浏览器相同的cookie

Han*_*ger 12 php cookies curl

我有一个PHP脚本代表浏览器执行HTTP请求,并输出响应浏览器.问题是当我点击此页面上浏览器中的链接时,它会抱怨cookie变量.我假设它需要网站的浏览器cookie.

如何拦截并转发到远程站点?

PiT*_*ber 11

这就是我将所有浏览器cookie转发为curl并将curl请求的所有cookie返回给浏览器的方式.为此我需要解决一些问题,比如从curl获取cookie,解析http头,发送多个cookie和会话锁定:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// get http header for cookies
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);

// forward current cookies to curl
$cookies = array();
foreach ($_COOKIE as $key => $value)
{
    if ($key != 'Array')
    {
        $cookies[] = $key . '=' . $value;
    }
}
curl_setopt( $ch, CURLOPT_COOKIE, implode(';', $cookies) );

// Stop session so curl can use the same session without conflicts
session_write_close();

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

// Session restart
session_start();

// Seperate header and body
list($header, $body) = explode("\r\n\r\n", $response, 2);

// extract cookies form curl and forward them to browser
preg_match_all('/^(Set-Cookie:\s*[^\n]*)$/mi', $header, $cookies);
foreach($cookies[0] AS $cookie)
{
     header($cookie, false);
}

echo $body;
Run Code Online (Sandbox Code Playgroud)

  • 您可能还想添加:curl_setopt($ ch,CURLOPT_USERAGENT,$ _SERVER ['HTTP_USER_AGENT']); (2认同)

Ctr*_*rlX 7

事实上,这是可能的.您只需要获取浏览器的cookie并将其作为参数传递给curl以模仿浏览器.这就像一个会议顶...

这是一个示例代码:

// Init curl connection
$curl = curl_init('http://otherserver.com/');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
// You can add your GET or POST param

// Retrieving session ID 
$strCookie = 'PHPSESSID=' . $_COOKIE['PHPSESSID'] . '; path=/';    

// We pass the sessionid of the browser within the curl request
curl_setopt( $curl, CURLOPT_COOKIE, $strCookie ); 

// We receive the answer as if we were the browser
$curl_response = curl_exec($curl);
Run Code Online (Sandbox Code Playgroud)

如果您的目的是调用另一个网站,它的效果非常好,但是如果您调用Web服务器(这与启动curl命令相同),则会失败.这是因为您的会话文件仍然被此脚本打开/锁定,因此您调用的URL无法访问它.

如果要绕过该限制(在同一服务器上调用页面),则必须在执行curl之前使用此代码关闭会话文件:

$curl = curl_init('http://sameserver.com/');
//...
session_write_close();
$curl_response = curl_exec($curl);
Run Code Online (Sandbox Code Playgroud)

希望这会帮助别人:)