How to redirect in PHP
If you require to redirect a user from one web page to another by using PHP, you may use the header function.
By definition, the PHP header function sends the raw HTTP header to a client. A simple example of redirecting by header function is:
1 2 3 4 5 |
<?php header('Location: http://www.google.com/'); ?> |
A few points should be noted as using the header function:
- You should call the header function before any output e.g. using echo, HTML tags etc. are sent to the browser.
- If you are using HTML code then it should be used before <!DOCTYPE> declaration.
- You have to provide the absolute URL in the header function, otherwise, an error is generated. See the examples section below.
- You should use either exit() or die() after the header() function.
The example of redirecting to another URL
As you execute this code, you will be redirected to the google.com by using header function with “Location:” header. Copy the code in your IDE and execute in your local machine with PHP 4, 5 or 7 configured:
1 2 3 4 5 6 7 |
<?php header('Location: http://www.google.com/'); exit() ?> |
Note that, the default redirect code is 302 which means it is a temporary redirect. This is important if you are concerned about SEO as well.
The 301 response code specifies permanent redirect.
So, if you use the header function without specifying the HTTP response code then search engines (Google, Bing etc.) take this as a temporary redirect. This may be useful if you are redirecting the users to another page while current page/website is under maintenance or down for some reason etc.
If you have optimized the calling page with SEO then it may pass the page rank (link juice) to the new URL (as per latest documentation). However, if you are sure the redirect is permanent then you should specify 301 redirect so the redirected page gets all the effort you put on the calling page.
The example code for redirecting permanently:
1 2 3 4 5 6 7 |
<?php header('Location: http://www.jquery-az.com', true, 301); exit; ?> |
For sending the 503 response code, the sample code is:
1 2 3 4 5 6 7 |
<?php header('Location: http://www.jquery-az', true, 503); exit; ?> |
Note: the 503 response code means “Service Unavailable”.
You may learn more about the HTTP /1.1 status code here.