Thursday, 21 February 2013

PHP Redirect(301 Permanent and 302 temporary redirect) or header() Function in php | PHP Tutorial for Beginners

In this tutorial of php code for beginners we will see how to use php redirection function like 301 temporary redirect and 302 permanent redirect.

Some time we want to redirect user to specific page when certain condition are true or false. At this time our php allow you to use his function called header() to redirect the user appropriate location. Simple example to use redirect is in any login form. If username and password are correct then redirect user to this dashboard else redirect him again to login form.

PHP Redirect Code


<?php 
header("HTTP/1.1 301 Moved Permanently"); 
header("Location: http://www.phpredirecttutorial.com"); 
?>
It is 301 permanent redirect, because we have used "header("HTTP/1.1 301 Moved Permanently")". If you want to use 302 temporary redirect simply skip this line and write below code.

<?php 
header("Location: http://www.phpredirecttutoriale.com"); 
?>
NOTE:- This would result in a "302 Moved Temporarily" redirect instead of a 301 one. This should be avoided as permanent redirects are more search engine friendly and should be used where possible.


Hope this php tutorial is useful for you. Keep following www.phpcodeforbeginner.blogspot.in for more help.

2 comments:

  1. renee skolnick3 June 2013 19:15


    Hi,

    I am bringing in in a new website and plan on setting up 301 redirects in the .htaccess file.

    Do I need to keep the OLD .html pages on the server?

    ReplyDelete