2010-04-02 130 views
6

我使用下面的代碼:捲曲重定向,不工作?

$agent= 'Mozilla/5.0 (Windows; U; Windows NT 5.1; pl; rv:1.9) Gecko/2008052906 Firefox/3.0'; 

$ch = curl_init(); 

curl_setopt($ch, CURLOPT_USERAGENT, $agent); 

curl_setopt($ch, CURLOPT_URL, "www.example.com"); 

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 

curl_setopt($ch, CURLOPT_HEADER, 0); 

$output = curl_exec($ch); 

echo $output; 

但它重定向到這樣的:

http://localhost/aide.do?sht=_aide_cookies_ 

而不是到URL頁面。

任何人都可以幫我解決我的問題嗎?

+0

如果你用四個空格縮進你的代碼,它會更具可讀性。 – 2010-04-02 08:49:21

回答

13
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); 

http://docs.php.net/function.curl-setopt說:

CURLOPT_FOLLOWLOCATION
TRUE遵循任何「位置:」頭,服務器發送的HTTP標頭的一部分(注意這是遞歸的,PHP將遵循儘可能多的「位置:「發送它的標題,除非設置了CURLOPT_MAXREDIRS)。
+1

+1我喜歡它,當我通過單一搜索找到我正在尋找的SO時 – Endophage 2011-06-13 22:34:20

8

如果它是由URL重定向纔看到下面的代碼,我已經證明它給你,讓你可以直接輕鬆地使用它&,你已經兩個主要的捲曲選項控制URL重定向(CURLOPT_FOLLOWLOCATION/CURLOPT_MAXREDIRS):

// create a new cURL resource 
$ch = curl_init(); 

// The URL to fetch. This can also be set when initializing a session with curl_init(). 
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/"); 

// The contents of the "User-Agent: " header to be used in a HTTP request. 
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; pl; rv:1.9) Gecko/2008052906 Firefox/3.0"); 

// TRUE to include the header in the output. 
curl_setopt($ch, CURLOPT_HEADER, false); 

// TRUE to return the transfer as a string of the return value of curl_exec() instead of outputting it out directly. 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 

// TRUE to follow any "Location: " header that the server sends as part of the HTTP header (note this is recursive, PHP will follow as many "Location: " headers that it is sent, unless CURLOPT_MAXREDIRS is set). 
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); 

// The maximum amount of HTTP redirections to follow. Use this option alongside CURLOPT_FOLLOWLOCATION. 
curl_setopt($ch, CURLOPT_MAXREDIRS, 10); 

// grab URL and pass it to the output variable 
$output = curl_exec($ch); 

// close cURL resource, and free up system resources 
curl_close($ch); 

// Print the output from our variable to the browser 
print_r($output); 

上述代碼處理URL重定向問題,但它不處理cookie(您的本地主機URL似乎是處理cookie)。如果要對付來自卷邊資源餅乾,那麼你可能得給下面捲曲選項一看: CURLOPT_COOKIE CURLOPT_COOKIEFILE CURLOPT_COOKIEJAR

欲瞭解更多詳情,請按照下面的鏈接: http://docs.php.net/function.curl-setopt