PHP - How to Redirect

PHP - How to Redirect

PHP, PHP Redirect, Redirect

Creating a PHP redirect allows you to redirect a user to a different page on your site. PHP redirection typically is used when you are attempting to permanently redirect the page, therefore it should return a 301 Moved Permanently response. If you are only temporarily redirecting you should use a 302 Found response. Check below for a examples of each implementation. 

 

Use the PHP Header function

As you can see below creating the redirect is a one liner. We are using the header() method to change the location of the page. In the example below we are not passing a $statusCode to header() so the response will be a 302. Also notice the call to die() on the next line, this is the equivalent to exit() and will stop page execution.

header('Location: '.$url);
die(); // Use if you are killing page execution

Creating a helper for PHP Redirects

Helper methods are always fun, especially when dealing with a PHP redirect! Below we are combining the header() and die() calls into a single method which also makes use of header() overload and passes in a $statusCode parameter. This method should work in all scenarios and obviously very flexible as it's only a few lines of code.

function Redirect($url, $statusCode = 303)
{
   header('Location: ' . $url, true, $statusCode);
   die();
}