2012-06-20 38 views
0

我想用curl为我的网站创建一个登录名来管理一些东西。 因此,我必须使用相同的cookie发出多个curl请求完成一个PHP后的几个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); 

我不太清楚哪个版本更好,我有点担心的cookie。 还是有没有更好的版本,我没有想到?

回答

0

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

第二个选项打开每次/关闭HTTP连接,这TCP握手耗时

注意:这仅仅是对同一服务器发出当然,连接相关...

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