How to Redirect a Web Page with PHP

  1. Use header() function with exit()

In PHP you can use the header() function (it sends a raw HTTP header to a client) to make a redirect from one web page to another.

It is possible to use the header() function to send a new HTTP header, but this must be sent to the browser before any HTML or text (e.g. before the remark).

Example

<?php 
  header('Location: //www.w3docs.com');
// or die();

  exit();
?>

The usage of exit () on a redirect is to prevent the page from showing up the remaining content (i.e restricted pages).

  1. Using header function with ob_start() and ob_end_flush()

Example

<?php ob_start(); //this should be first line of your page header('Location: target-page.php'); ob_end_flush(); //this should be last line of your page ?>

  1. Using Helper Function

Example

function Redirect($url, $permanent = false) {
 header('Location: ' . $url, true, $permanent ? 301 : 302);
 exit();
 }
Redirect('//www.w3docs.com/', false);

Note: This function doesn't support the 303 status code

This example is more flexible:

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

  1. There are special cases if you're running in CLI (redirects cannot happen and thus shouldn't exit()) or if your webserver is running PHP as a (F) CGI (it needs a previously set Statusheader to properly redirect).

Example

function Redirect($url, $code = 302){
  if (strncmp('cli', PHP_SAPI, 3) !== 0) {
    if (headers_sent() !== true) {
      if (strlen(session_id()) > 0) {// if using sessions

        session_regenerate_id(true); // avoids session fixation 	attacks

        session_write_close(); // avoids having sessions lock other requests

      }

      if (strncmp('cgi', PHP_SAPI, 3) === 0) {
        header(sprintf('Status: %03u', $code), true, $code);
      }

      header('Location: ' . $url, true, (preg_match('~^30[1237]$~', $code) >  0) ? $code : 302);
    }
    exit();
  }
}

Learn more about how to redirect web pages with HTML, JavaScript, Apache and Node.js