2010-10-31 82 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