【发布时间】:2025-07-27 21:25:02
【问题描述】:
我正在完成一个项目,但我需要比较 HTTP 状态代码是否与另一个相同。我有一个大算法,我减少了它们,我发现了问题: 我有一个名为“$file_headers”的数组,在 [“Status”] 位置保存“HTTP/1.1 301 永久移动”,在 if 子句中我比较“HTTP/1.1 301 永久移动”(这显然是相同),但我的代码和我说的不一样。我使用 cURL 检测 HTTP 状态代码。我的 PHP 代码如下:
<?php
// create curl resource
$ch = curl_init();
// set url
curl_setopt($ch, CURLOPT_URL, "fb.com");
//return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//enable headers
curl_setopt($ch, CURLOPT_HEADER, 1);
//get only headers
curl_setopt($ch, CURLOPT_NOBODY, 1);
// $output contains the output string
$output = curl_exec($ch);
// close curl resource to free up system resources
curl_close($ch);
$data = explode("\n",$output);
$headers_one = $data;
$headers_two = array();
$headers_two['Status'] = $data[0];
array_shift($data);
foreach($data as $part){
$middle = explode(":",$part);
$msg = null;
if(sizeof($middle) > 2){
if(strpos($middle[0],"Location") === false){
for($i = 1; $i <= sizeof($middle)-1;$i++){
$msg .= $middle[$i];
}
} else {
for($i = 1; $i <= sizeof($middle)-1;$i++){
if($i == 1){
$msg .= $middle[$i] . ":";
} else {
$msg .= $middle[$i];
}
}
}
} else if(isset($middle[1])){
$msg = $middle[1];
}
$headers_two[trim($middle[0])] = trim($msg);
}
array_pop($headers_one);
array_pop($headers_one);
array_pop($headers_two);
$file_headers = $headers_two;
if($file_headers["Status"] === ("HTTP/1.1 301 Moved Permanently") || $file_headers["Status"] === ("HTTP/1.1 301")){
echo "OK!";
} else {
echo "NO!";
}
//print all headers as array
/*echo "<pre>";
print_r($headers_one);
echo "</pre><br />";*/
echo "<pre>";
echo $file_headers["Status"];
echo "</pre>";
?>
如果有人可以帮助我,我将不胜感激。谢谢,祝开发者愉快!
【问题讨论】:
-
为什么你在
("HTTP/1.1 301 Moved Permanently")和("HTTP/1.1 301")这样的字符串上添加了额外的parenthesis,记住你是在比较===而不是==? -
因为阳光明媚,我忘记在我的简化算法中删除它,但在我的原始代码中是这样的: ("HTTP/" . $HTTPversions[$y] . " " . $StatusURL[ $x]->code . " " . $StatusURL[$x]->name)
标签: php arrays string curl http-status-codes