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.
header( "refresh:0; url=YOUR_REDIRECT_LINK" );
<?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
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.
header( "location: YOUR_REDIRECT_LINK" );
<?php header( "location: http://errorsea.com" ); ?>
Note: This method will not wait for a second and instantly redirect the page.
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 🙂