How To Redirect URL Using PHP header redirect?
Redirecting URL in PHP is very useful. In many purposes, developers need to redirect a page to a URL. Redirecting page into a specific URL is very easy and simple task. You just need a line of simple PHP code.
PHP header redirect code to redirect URL
Below is given the simple PHP code to redirect to a URL:
<?php header( 'Location: http://www.yoursite.com/page1.php' ) ; ?>
You can also put the page file name only if it is in the same directory like you can see in the below code snippet:
<?php header( 'Location: page1.php' ) ; ?>
Or by giving the directory name if it is inside a directory and the directory is also in the same directory where you need to place header redirect:
<?php header( 'Location: my_directory/page1.php' ) ; ?>
But do you know one thing, that after a header redirects in PHP the rest of below code also execute? But in many cases, you may not want these code to be run. So in this situation, the right way is using the PHP exit() function.
Below is the given code which will prevent from executing all the codes after PHP header redirection:
<?php header( 'Location: page1.php' ) ; exit() ?>
Now suppose, there is more than one header redirect like below code:
<?php header('Location: page1.php'); header('Location: http://google.com'); header('Location: http://twitter.com'); header('Location: http://facebook.com'); header("Location: http://170.187.134.184"); ?>
You will get your answer if you test the above code snippet on your server. You will see that the last one header redirect code is executing. it doesn’t matter how many header redirect code is there, it always executes the last one until you break the code using the PHP exit() function. Header redirects in PHP process after executing all the code if the PHP exit() function is not using the code.
So you have seen how easy it is to redirect URL in PHP programming language. I hope this tutorial will be helpful to you.
Leave a Reply