Blog

How to Code a PHP Redirect - PHP Header Redirect

Written by Codextiny | Dec 23, 2023 4:51:46 PM

Redirecting visitors in PHP is straightforward using the  header()  function. Here's how it works:

  1. Create a simple PHP file:
    Name it  index.php  and place it within the directory you want to initiate the redirect from.
  2. Add the following code to the file:

    <?php header("Location: http://www.destination-url.com/"); ?>
    Replace  http://www.destination-url.com/  with the actual URL you want users to be redirected to.

    You can also specify a file path instead of a URL:

    <?php header("Location: anotherDirectory/anotherFile.php"); ?>

  3. Save the file:
    When a visitor accesses this  index.php  file, they'll be seamlessly redirected to the specified URL or file.

Key points

  • Flexibility: The  header()  function can redirect to various file types, including HTML, Python, PHP, CGI, Perl, and compiled CGI programs.
  • Multiple uses: Redirections are valuable for tasks like
    • Moving visitors to updated pages
    • Forwarding to different sections of your website
    • Handling logins and access control