Learn how to create a redirect function without the help of any framework using plain PHP.

How to redirect to a page with plain PHP

In the latest years, an important number of developers work with any of the most famous PHP frameworks like Symfony, Laravel, CakePHP, Zend etc as the backend solution for an application or service.

Using a framework is a huge advantage, how many of you remember how to redirect to another website using PHP? Probably, you've forgotten isn't ? In this article you will learn how to redirect using PHP in case you want to refresh your memory or you simply need to know how to do it.

Basic redirection

Theoretically, a basical redirect feature will be componed by the following lines:

    header( 'Location: http://es.ourcodeworld.com/' ) ;
    // or die();

The header function expects a header with it's value within a string, in this case Location with takes as value a relative or absolute path (alternatively of a local path, a web URL including the domain). The usage of exit() on a redirect is to prevent the page from showing up the remaining content (i.e restricted pages).

By default, in the kind of redirection previously exposed is a temporal redirection, which means that any search engine like Google will ignore it in the positioning. Therefore, if you want to indicate to any search engine that a "A" page is now on "B", we need to specify the response code as third parameter in the header function:

    header('Status: 301 Moved Permanently', false, 301);
    header('Location: new/path.php');

Note: remember that the second parameter of the headers function is a boolean that indicates whether the header should replace previous or add a second header. A 301 redirect means that the page has permanently moved to a new location and a 302 redirect means that the move is only temporary.

Helper function

If you need to know how to redirect using plain PHP but you come from a framework background, this is probably the best solution for you, a redirect method. The following method illustrates the easiest implementation of a redirect function:

function redirect($url, $permanent = false){
    if (headers_sent() === false)
    	header('Location: ' . $url, true, ($permanent === true) ? 301 : 302);

// Redirect to external URLS
redirect('http://www.google.com/', false);
// Redirect with relative URL'S (or a file)

The $permanent parameter allow you to alternate between the response codes (301 and 302).

A redirection is basically, a bunch of HTTP headers. According to the HTTP protocol, the HTTP headers should be sent always before than any other content, that means that not any kind of character should be sent as response (echo, print_r or any other function that generates an ouput), not even a blank space.

Have fun !

Senior Software Engineer at Software Medico. Interested in programming since he was 14 years old, Carlos is a self-taught programmer and founder and author of most of the articles at Our Code World.