Back to Homepage
Wednesday 7 August 2024
17

How to redirect in PHP

Steps to Redirect in PHP

Need to redirect a user in PHP? Follow these easy steps:

1. Use the Header Function:

  • Place the following code at the beginning of your PHP script, before any HTML output:
<?php
     header("Location: http://www.example.com");
     exit();
     ?>

2. Ensure No Output Before the Header:

  • Make sure there is no whitespace or HTML before the header() function call to avoid errors.

3. Redirect with a Status Code:

  • Optionally, you can include an HTTP status code for the redirection:
<?php
     header("Location: http://www.example.com", true, 301);
     exit();
     ?>

4. Test the Redirection:

  • Run your PHP script and ensure it redirects to the specified URL correctly.
Share:
Created by:
Author photo

Jorge García

Fullstack developer