2017-06-14 59 views
0

迭代時,只有一次我在test.php下面的代碼創建的字符串:循環創造陣列,但在PHP

<?php 
$url = "http://pars.mp3hunt.me/r1.php"; 

$again = 1; 

while ($again == 1) { 
    $headers = get_headers($url, 1); 
    preg_match('/\b([3]\d\d)\b/', $headers[0], $matches); // 3XX error 
    if (count($matches) > 0) { 
     $url = $headers['Location']; 
    } else { 
     $again = 0; 
    } 
} 
if (is_array($url)) { 
    echo 'yes'; 
} 
print_r($url); 
?> 

r1.phpr2.php重定向。 r1.php有:

<?php 

$url="http://pars.mp3hunt.me/r2.php"; 
header('Location: ' . $url, true, 302); 
?> 

`r2.php有

<?php 

$url="http://pars.mp3hunt.me/r3.php"; 
header('Location: ' . $url, true, 302); 
?> 

r3.php有一些文字。

現在,當$url變量分配http://pars.mp3hunt.me/r1.php印刷$url是一個數組,並且當它被分配http://pars.mp3hunt.me/r2.php它是一個字符串。問題是爲什麼是這樣?我只在任何地方分配$url字符串。我也沒有宣佈$url作爲一個數組,並仍然在兩次重定向(迭代)後,它成爲一個數組,並在一次重定向(迭代)它是字符串。

+0

關於PHP變量的事情是,即使你沒有一個聲明爲數組,但如果它分配一個數組值也將被關成陣列。 – hungrykoala

+0

快速瀏覽一下,爲什麼問題依賴'get_headers'的返回值的答案,這個(也與流相關)的一些細節和示例在這裏:https://hakre.wordpress.com/2011/ 09/17/head-first-with-php-streams/ – hakre

+0

因爲'$ headers ['Location'];'是一個數組!所以這行'$ url = $ headers ['Location'];'使'$ url'成爲一個數組 – RiggsFolly

回答

0

你描述的是正常行爲。由於您在這裏處理重定向,因此默認情況下會執行HTTP GET請求,因此可能會有多個請求與get_headers

通過http://pars.mp3hunt.me/r2.php URL可以看到一個位置條目(因此是一個字符串),但使用http://pars.mp3hunt.me/r1.php URL可以看到兩個位置條目(因此也是一個數組)。

有關如何解析get_headers的結果和/或您如何控制行爲(例如,執行HTTP HEAD請求而不是GET請求),請參閱the link I've left in the comment。關於這一點,還有關於Stackoverflow的其他信息。

例子:

$urls = [ 
    "http://pars.mp3hunt.me/r2.php", 
    "http://pars.mp3hunt.me/r1.php" 
]; 

foreach ($urls as $url) { 
    $headers = get_headers($url, 1); 

    echo $url, ":\n"; 
    var_dump($headers['Location']); 
    echo "\n"; 
} 

輸出:

http://pars.mp3hunt.me/r2.php: 
string(29) "http://pars.mp3hunt.me/r3.php" 

http://pars.mp3hunt.me/r1.php: 
array(2) { 
    [0]=> 
    string(29) "http://pars.mp3hunt.me/r2.php" 
    [1]=> 
    string(29) "http://pars.mp3hunt.me/r3.php" 
} 
+0

好吧,幫助了我。謝謝 –