一个完成后PHP几个curl请求

时间:2012-06-20 17:31:43

标签: 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);

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

2 个答案:

答案 0 :(得分:0)

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

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

注意:这仅与对同一服务器的连接有关,当然......

答案 1 :(得分:0)

使用第一个添加以下卷曲选项:

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");