How to make redirect in PHP

Sometime it may happen that, you will have to purchase a new domain but you realize that the older one is more popular than what you can do is that, you can transfer the files on new server and can write a simple redirection code on older server

For ex: If you have one url named as www.example1.com/test.php and now you have taken new url named as www.example2.com/xyz.php. then instead of writing the same code twice, you have to transfer the files on the new server and have to write a script on example1.com/test.php
which can redirect this to www.example2.com/xyz.php


Lets have one more scenario, If you are writing a login script then it is possible that you may have two actions :

a) If the login success, then you have to redirect the profile.php page

b) If the login fails, then it should redirect on login_failed.php page

Now the main question comes that how we can redirect from one page to another. It is very simple in php.

To redirect from one page to another in php, you can simply use header() funtion. It can be used as follow

header("Location:your_new_url.php");

Sometimes, when you use xampp for your Apache server then it may raise some error like Headers already sent

Then it is better to use ob_start() at the top of the php file to ignore this warning.

Leave a Reply

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