PHP Redirect to Another Page with Examples

Last Updated on October 10, 2022 by Roshan Parihar

In this tutorial, learn how to redirect to another page in PHP. The short answer is to use the header() of PHP to make redirection to other pages.

You can also use the script with the echo statement of PHP. Let’s find out the different examples given below.

Method 1: Redirect to Another Page Using header() Function in PHP

To redirect to another page in PHP, you can use the header() function and pass the URL as the argument. It is the relative URL that you have to specify for redirection as given in the example below.

You can add redirection after the successful execution of PHP codes. Suppose, if you want to delete the items from the database, you can perform a delete query and redirect after the successful deletion of items. The exit function is used here to prevent the remaining code from loading after encountering redirection.

Method 2: Redirect Using Script window.location = '' in PHP Echo

If you want to redirect in PHP using a script, you can echo <script> and use window.location = 'https://yourdomain.com/anotherpage.php/' inside it. Also, change the URL with your real URL for redirection in PHP.

The above example contains the echo statement with a redirection URL. When the execution in PHP reaches this code, it redirects to the specified URL.

Method 3: Permanent (301) and Temporary (307) Redirection in PHP

In addition to the above all redirections in PHP, you can also use the header() function for temporary and permanent redirection. See the examples given below for temporary and permanent redirection.

Permanent Redirection in PHP

The permanent redirection is useful to pass SEO ranking benefits from the old URL to the new URL. If you want to change the old URL to a new URL and want the search engine to rank the new URL only, you should consider making permanent redirection. Use 301 for permanent redirection as given below.

Temporary Redirection in PHP

Temporary redirection is useful when you want to temporarily redirect the URL to the new URL. You have to use 307 for temporary redirection as given below.

You May Also Like to Read

Leave a comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.