循环在PHP中迭代两次时创建数组,但在PHP中仅迭代一次时创建字符串
我在循环在PHP中迭代两次时创建数组,但在PHP中仅迭代一次时创建字符串,php,arrays,loops,http,redirect,Php,Arrays,Loops,Http,Redirect,我在test.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) {
test.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);
?>
`r2.php已经
<?php
$url="http://pars.mp3hunt.me/r3.php";
header('Location: ' . $url, true, 302);
?>
php有一些文本
现在当
$url
变量被赋值http://pars.mp3hunt.me/r1.php
打印的$url
是一个数组,当它被分配http://pars.mp3hunt.me/r2.php
它是一个字符串。问题是为什么会这样?我只分配$url
所有的字符串。我也没有将$url
声明为数组,但在两次重定向(迭代)后,它仍然成为数组,在一次重定向(迭代)时,它是字符串。您描述的是正常行为。当您在这里处理重定向时,在默认情况下执行HTTP GET请求时,可以有多个请求
使用http://pars.mp3hunt.me/r2.php
URL您会看到一个位置条目(因此是一个字符串),但带有http://pars.mp3hunt.me/r1.php
URL您会看到两个位置条目(因此是一个数组)
请参阅如何解析get_headers
的结果和/或如何控制行为(例如,执行HTTP HEAD请求而不是get请求)。关于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"
}
PHP变量的一个特点是,即使您不将一个变量声明为数组,但如果为它分配了一个数组值,它也将转换为一个数组。快速浏览一下,为什么这个问题的答案依赖于
get_headers
的返回值,其中的一些细节(也与流相关)这里有一些例子:因为$headers['Location']代码>是一个数组!!!所以这一行$url=$headers['Location']
使$url
成为array@RiggsFolly:是,但它并不总是数组。它取决于请求链中重定向的数量。$header['Location']
是一个字符串,您可以检查它如果(是数组($headers['Location']){echo'yesheader是数组';}
确定这对我有帮助。谢谢
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"
}