PHP Redirect Pages

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

Redirect Pages In PHP

Here we are going to focus on redirecting a web page using PHP. Generally, we need to redirect a page after user authentication and user registration. We also redirect users to 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.

Read Also: Force HTTP to HTTPS Redirect

Method 1: Header Refresh Method

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 will simply need to change the refresh value.

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 get redirected to another page.

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

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

*/ 
?>

Method 2: Header Location Method

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" ); 
?>

Conclusion

This article has given a complete overview of PHP redirection and its methods.

We hope you have gained a complete understanding of the OOPs concepts in PHP programming. In case you want to learn about the other concepts, refer to our PHP Tutorial, PHP MySQL, PHP Form and PHP OOP sections. Happy Learning!

Leave a Reply

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