我需要重定向到一个未知地址。如果地址不可用,我想向用户显示一条消息。怎么做?
<?php
header("Location: http://www.example.com/");
exit;
?>
最直接的方法是只检索页面:
if (file_get_contents('http://www.example.com/') !== false) {
header("Location: http://www.example.com/");
exit;
}
http://php.net/manual/en/function.file-get-contents.php
但是,这只会告诉您该页面上是否有可用的东西。例如,它不会告诉您是否收到了 404 错误页面。
为此(并且为了节省下载整个页面的内存成本),您可以只get_headers()
使用 URL:
$url = "http://www.example.com/";
$headers = get_headers($url);
if (strpos($headers[0],'200 OK') !== false) { // or something like that
header("Location: ".$url);
exit;
}
您可以检查 url 是否存在然后重定向:
$url = 'http://www.asdasdasdasd.cs';
//$url = 'http://www.google.com';
if(@file_get_contents($url))
{
header("Location: $url");
}
else
{
echo '404 - not found';
}
你可以使用 curl
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
$output = curl_exec($ch);
if(curl_errno($ch)==6)
echo "page not found";
else
header("Location: http://www.example.com/");
curl_close($ch);