PHP 几个 curl 请求完成后的一个



我想用curl为我的网站创建一个登录名来管理一些东西。因此,我必须使用相同的 cookie 发出多个 curl 请求

现在我想知道什么代码可以更好地实现这一点。这样更好吗:

$CookieFile = 'cookies/'. uniqid() . '.txt';
file_put_contents($CookieFile, '');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $Url);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $PostData1);
curl_setopt($ch, CURLOPT_COOKIEFILE, $CookieFile);
curl_setopt($ch, CURLOPT_COOKIEJAR, $CookieFile);
$result1 = curl_exec($ch);
curl_setopt($ch, CURLOPT_URL, $Url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $PostData2);
$result2 = curl_exec($ch);
curl_close($ch);

还是这样做更好

$CookieFile = 'cookies/'. uniqid() . '.txt';
file_put_contents($CookieFile, '');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $Url);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $PostData1);
curl_setopt($ch, CURLOPT_COOKIEFILE, $CookieFile);
curl_setopt($ch, CURLOPT_COOKIEJAR, $CookieFile);
$result1 = curl_exec($ch);
curl_close($ch);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $Url);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $PostData2);
curl_setopt($ch, CURLOPT_COOKIEFILE, $CookieFile);
curl_setopt($ch, CURLOPT_COOKIEJAR, $CookieFile);
$result2 = curl_exec($ch);
curl_close($ch);

不太确定哪个版本更好,我有点担心饼干。或者有没有我没有想到的更好的版本?

第一个更好,因为它可以利用Keep-Alive

第二个选项每次都打开/关闭 http 连接,并且此 TCP 握手非常耗时

注意:当然,这只与与同一台服务器建立的连接有关......

使用第一个选项并添加以下 curl 选项:

curl_setopt($ch, CURLOPT_FORBID_REUSE, 0);
curl_setopt($ch, CURLOPT_FRESH_CONNECT, 0);
curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
curl_setopt($ch, CURLOPT_USERAGENT, "valid user agent");

最新更新