Tutorial – How To Redirect From One Page To Another In PHP

In PHP, when you want to redirect a from one page to another, you need to do so by responding with a header. The header response will tell the browser how they will need to redirect the user.

header('Location: https://ua1.us/');

Setting The Response Code

When redirecting a user from one page to another, it is a good practice to respond with a reason why you are redirecting them. And you will do so by sending a response code back to the browser using the php function http_response_code(). The typical response code for a redirect should be a 301. This indicates that the page you are redirecting too, will permanently replace the one you originally requested. The other common response code for redirects are 302. This code is typically used for indicating a temporary page replacement.

Why We Should Exit The PHP Script

In the example above, you may have noticed that there is a function called exit() called right after we call the header() function. The reason for this is because we want to stop any further execution of the PHP script. Even after we call the header() function, the PHP function will continue to execute until the browser has received the response and release it’s connection to the server running the PHP script.

Leave a Reply