I need to redirect to an unknown address. If the address is not available I would like to show a message to the user. How to do that?
<?php
header("Location: http://www.example.com/");
exit;
?>
I need to redirect to an unknown address. If the address is not available I would like to show a message to the user. How to do that?
<?php
header("Location: http://www.example.com/");
exit;
?>
The most direct method is to just retrieve the page:
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
However, this only tells you if SOMETHING is available at that page. It won't tell you if, for instance, you got a 404 error page instead.
For that (and to save the memory cost of downloading the whole page), you can just get_headers()
for the URL instead:
$url = "http://www.example.com/";
$headers = get_headers($url);
if (strpos($headers[0],'200 OK') !== false) { // or something like that
header("Location: ".$url);
exit;
}
You can check if url exist then redirect:
$url = 'http://www.asdasdasdasd.cs';
//$url = 'http://www.google.com';
if(@file_get_contents($url))
{
header("Location: $url");
}
else
{
echo '404 - not found';
}
You can do it using 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);