-1

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;
?>
10
  • 2
    Define "not available"
    – Sebas
    Commented May 9, 2013 at 13:49
  • 2
    Test the website first with file_get_contents. Then show an error if your website can't connect.
    – Dave Chen
    Commented May 9, 2013 at 13:49
  • 1
    ah ping, but the web server could still be down.
    – Dave Chen
    Commented May 9, 2013 at 13:51
  • 1
    see stackoverflow.com/questions/2280394/…
    – worenga
    Commented May 9, 2013 at 13:53
  • 1
    @mightyuhu best solution, checks headers as well
    – Dave Chen
    Commented May 9, 2013 at 13:56

3 Answers 3

2

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;
}
6
  • The OP will need to do additional checks on the page itself. In any case, control is lost from there on.
    – Dave Chen
    Commented May 9, 2013 at 13:53
  • file_get_contents downloads the whole page, for the sake of availbility /memory this is a little much.
    – worenga
    Commented May 9, 2013 at 13:55
  • 2
    get_headers() might just be enough here.
    – Ja͢ck
    Commented May 9, 2013 at 13:57
  • @Jack So noted, editing. Commented May 9, 2013 at 14:03
  • does get_headers() ignore the body content, in other words, does it save bandwidth on both sides?
    – Dave Chen
    Commented May 9, 2013 at 15:56
0

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';
}
0

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);  

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.