How to Redirect Page in PHP [All Methods]

There are lots of methods to redirect page like refresh redirect from META tag, redirect from PHP, and window.location method in JavaScript.

Here we are going to focus on redirecting a web page using PHP. Especially, we need to redirect a page after user authentication and user registration. We also redirect users on some specific conditions in our PHP script.

There are two main methods to redirect the user. However, both methods work on the header() function in PHP.

Method 1: Header Refresh Method in PHP

In this method, we need to pass refresh time and link to the web page where we want to redirect users.

Syntax

header( "refresh:0; url=YOUR_REDIRECT_LINK" );

Example 1

<?php
header( "refresh:0; url=http://errorsea.com" );
/*

your content goes here........

*/
?>

Note: Here refresh: 0; shows that page will wait for 0 seconds and redirect after that, which means the page will be instantly redirected. If you want users to wait for a few seconds and redirect after that, you need to change refresh value, and it’s done.

Read Also: Registration and Login form with PHP

Example 2

In this example, users will wait at the current page for 5 seconds and then redirected to another page.

<?php 
header( "refresh:5; url=http://errorsea.com" ); 
/* 

your content goes here........ 

*/ 
?>

Method 2: Header Location Method in PHP

This method is often used in PHP scripts to redirect pages instantly.

Syntax

header( "location: YOUR_REDIRECT_LINK" );

Example 1

<?php 
header( "location: http://errorsea.com" ); 
?>

Note: This method will not wait for a second and instantly redirect the page.

Example 2

We can use the sleep() method of PHP along with the above method to delay redirect for a few seconds. If we need to wait, users for 5 or 10 seconds we just need to use sleep(5) or sleep(10) before the header method.

<?php
sleep(5);
header( "location: http://errorsea.com" ); 
?>

I hope now you have a complete understanding of PHP redirection and its methods.

Enjoy coding 🙂

One thought on “How to Redirect Page in PHP [All Methods]

Leave a Reply

Your email address will not be published. Required fields are marked *

Read previous post:
How to Create a Responsive Table Using CSS

Responsive design is the primary need to create a good website nowadays. So, a responsive website needs a responsive table....

Close