Tuesday, December 10, 2013

PHP Tip - Redirecting to Another Page


There are times where you need to redirect the user to another page. For example, after the user has successfully registered as a user at your site, you might want to redirect them to the login page. As such, you need to be able to programmatically redirect the user to the target page.

To redirect the user to another page using PHP, you can use the header() function, like this:

<?php   
header('Location: anotherpage.php');   
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN">

This snippet of code must be placed at the top of the document, before the DOCTYPE element. The above code will automatically redirect the user to anotherpage.php whenever the user loads it.

However, if you want to programmatically redirect the user based on certain conditions (such as user successfully registering at your site), you have to do a little more work. The following code snippet redirects the user after injecting a delay of five seconds:

//--redirect to another page---
$delay = 5;  //---five seconds---
$redirectPageUrl = "login.php";
header( "Refresh: $delay; url=$redirectPageUrl" );
echo "You will now be redirected to the login page, after $delay seconds.";
exit();

The above snippet of code will redirect the user to the login.php page. Be aware though, that the above snippet must be accompanied by the following snippet, placed at the top of your PHP page:

<?php
ob_start();
?>

The ob_start() function turns the output buffer on so that no HTML code is sent to the client until the entire PHP script has been processed. If you don’t do that, by the time the header() function performs a redirection it would be too late as HTML code has already been sent to the client. 

No comments: