2012-01-05 207 views
2

我想在PHP中使用cURL獲取重定向URL。使用cURL獲取重定向URL

我目前使用的代碼是:

public function request($uri = null) 
{ 
    $redirects = 0; 

    if ($uri === null) { 
     $uri = $this->getUri(); 
    } 

    while ($redirects < $this->options['maxredirects']) { 
     $ch = curl_init(); 
     curl_setopt($ch, CURLOPT_URL, $uri); 

     curl_setopt($ch, CURLOPT_USERAGENT, $this->options['useragent']); 
     curl_setopt($ch, CURLOPT_HEADER, 0); 
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
     curl_setopt($ch, CURLOPT_TIMEOUT, $this->options['timeout']); 

     $result = curl_exec($ch); 
     $info = curl_getinfo($ch); 

     $this->addResult($result, $info); 

     if (floor($info['http_code']/100) != 3) { 
      return null; 
     } 

     $redirects++; 
    } 
} 

我沒有什麼用CURLOPT_FOLLOWLOCATION,因爲(如果錯了指正),可自動跟蹤重定向。

我一直希望它會在curl_getinfo(),但事實並非如此。它看起來像我必須啓用CURLOPT_HEADER並解析頭來獲得'下一個'的URL。

  • 這是正確的嗎?
  • 如果「是」,我將如何解析頭文件?例如。我可以安全explode()上的字符串\n找到的項目以Location:開頭?

回答

2

是的,你設置CURLOPT_HEADERtrue,然後通過與\r\n爆炸它解析字符串。 還有其他的方式,但不知道它們在你的情況下是否有效 - get_headers()http://www.php.net/manual/en/function.http-head.php

+0

而且我將如何區分響應中的'headers'和'body'? – PeeHaa 2012-01-05 22:21:03

+2

標題和正文由'\ r \ n \ r \ n'分隔。如果你不想要身體,你也可以設置'CURLOPT_NOBODY'。 – salathe 2012-01-05 22:25:31

+0

他們是'\ n'或'\ r \ n'分隔的。或者是這個IIS與Apache? – PeeHaa 2012-01-05 22:25:52