Mild Fuzz
Mild Fuzz

Reputation: 30691

Checking redirect in PHP before actioning

Is there a way to check if the server responds with an error code before sending a user there?

Currently, I am redirecting based on user editable input from the backend (client request, so they can print their own domain, but send people elsewhere), but I want to check if the URL will actually respond, and if not send them to our home page with a little message.

Upvotes: 1

Views: 548

Answers (3)

David Snabel-Caunt
David Snabel-Caunt

Reputation: 58361

You can do this with CURL:

$ch = curl_init('http://www.example.com/');

//make a HEAD request - we don't need the response body
curl_setopt($ch, CURLOPT_NOBODY, true);

// Execute
curl_exec($ch);

// Check if any error occured
if(!curl_errno($ch))
{
 $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); //integer status code
}

// Close handle
curl_close($ch);

You can then check if $httpCode is OK. Generally a 2XX response code is ok.

Upvotes: 1

Baylor Rae'
Baylor Rae'

Reputation: 4010

I don't understand what you mean by making sure the URL will respond. But if you want to display a message you can use a $_SESSION variable. Just remember to put session_start() on every page that will use the variable.

So when you want to redirect them back to the home page. You could do this.

// David Caunt's answer
$ch = curl_init('http://www.example.com/');

// Execute
curl_exec($ch);

// Check if any error occured
if(!curl_errno($ch))
{
 $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); //integer status code

 // My addition
 if( $httpCode >= 200 && $httpCode < 300 ) {
   // All is good
 }else {
   // This doesn't exist

   // Set the error message
   $_SESSION['error_message'] = "This domain doesn't exist";

   // Send the user back to the home page
   header('Location: /home.php'); // url based: http://your-site.com/home.php
 }
 // My addition ends here

}

// Close handle
curl_close($ch);

Then on your home page, you'll something like this.

// Make sure the error_message is set
if( isset($_SESSION['error_message']) ) {

  // Put the error on the page
  echo '<div class="notification warning">' . $_SESSION['error_message'] . '</div>';
}

Upvotes: 0

user137621
user137621

Reputation:

You could try the following, but beware that this is a seperate request to the redirect, so if something goes wrong in between then a user can still get sent to an erroneous location.

$headers = get_headers($url);
if(strpos($headers[0], 200) !== FALSE) {
  // redirect to $url
} else {
  // redirect to homepage with error notice
}

The PHP manual for get_headers(): http://www.php.net/manual/en/function.get-headers.php

Upvotes: 0

Related Questions