2010-10-31 24 views
24

我目前使用curl來填充表單,但在完成後,處理表單的其他腳本被重定向到其他url,現在我想要獲取url,腳本重定向到一個變量。cURL,獲取重定向url到一個變量

謝謝..

+0

可能重複[如何使用cURL獲取目標URL?](http://stackoverflow.com/questions/1439040/how-can-i-get-the- destination-url-using-curl) – 2016-05-26 17:00:22

回答

32

你會使用

curl_setopt($CURL, CURLOPT_HEADER, TRUE); 

,並解析其標頭的location

+0

+1錯過了那一點:) – Sarfraz 2010-10-31 11:06:16

+0

沒問題,使用post字段會發送數據,然後服務器會重定向,並且當數據輸出爲響應時,curl將選擇那個,那麼位置標題應該在那裏。 – RobertPitt 2010-10-31 11:07:57

3

您可能希望將CURLOPT_FOLLOWLOCATION設置爲true。

或者將CURLOPT_HEADER設置爲true,然後使用regexp獲取位置標題。

+0

也注意到這個PHP安全模式,http://www.php.net/manual/en/function.curl-setopt.php#95027 – RobertPitt 2010-10-31 11:08:34

8

在這裏我得到資源http標題,然後我將標題解析到數組$ retVal中。我得到了代碼從這裏(http://www.bhootnath.in/blog/2010/10/parse-http-headers-in-php/)解析頭你也可以使用http://php.net/manual/en/function.http-parse-headers.php如果你有(PECL pecl_http> = 0.10.0)

 $ch = curl_init(); 
     $timeout = 0; 
     curl_setopt ($ch, CURLOPT_URL, $url); 
     curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout); 
     curl_setopt($ch, CURLOPT_HEADER, TRUE); 
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
     curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1); 
     // Getting binary data 
     $header = curl_exec($ch); 
     $retVal = array(); 
     $fields = explode("\r\n", preg_replace('/\x0D\x0A[\x09\x20]+/', ' ', $header)); 
     foreach($fields as $field) { 
      if(preg_match('/([^:]+): (.+)/m', $field, $match)) { 
       $match[1] = preg_replace('/(?<=^|[\x09\x20\x2D])./e', 'strtoupper("\0")', strtolower(trim($match[1]))); 
       if(isset($retVal[$match[1]])) { 
        $retVal[$match[1]] = array($retVal[$match[1]], $match[2]); 
       } else { 
        $retVal[$match[1]] = trim($match[2]); 
       } 
      } 
     } 
//here is the header info parsed out 
echo '<pre>'; 
print_r($retVal); 
echo '</pre>'; 
//here is the redirect 
if (isset($retVal['Location'])){ 
    echo $retVal['Location']; 
} else { 
    //keep in mind that if it is a direct link to the image the location header will be missing 
    echo $_GET[$urlKey]; 
} 
curl_close($ch); 
+0

我試過這個解析代碼,它不工作,我是在「explode()」部分拋出幾個錯誤re:將數組轉換爲字符串 – bitwit 2012-04-05 20:49:38

+0

@ nico-limpika非常感謝:-)你的代碼幫了我很多。 'preg_replace'中的 – ravisoni 2013-08-27 09:41:10

+0

**'/ e修飾符已被棄用** **任何人都可以更新此答案嗎? – 2014-02-21 10:15:49

34

簡單的方法來找到重定向的URL(如果你不這樣做想提前知道)

$last_url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL); 
+3

它是'CURLINFO_REDIRECT_URL' – Sparky 2012-08-14 10:14:53

+0

我在這裏找不到CURLINFO_REDIRECT_URL http:// www.php.net/manual/en/function.curl-getinfo.php – 2012-08-15 04:41:15

+1

但我在這裏找到http://php.net/ChangeLog-5.php !!! CURLINFO_REDIRECT_URL被添加到5.3.7 - 但沒有記錄。但是從源頭上我假設這是(第一個)重定向url值,以防curl調用不使用自動重定向。所以我們知道下一個網址是什麼,以防萬一我們啓用了重定向。感謝@Sparky強迫我挖掘。 – 2012-08-15 04:59:53