Redirection in php

There are two ways for redirection in php.
  1. Use Header function
  2. Use meta tag
The best one is header function but there are some things that must be in your mind if you want to redirect user successfully to the required page. Below is the working demonstration of header function

1) Redirection using header function

header("location:yourdesiredpage.php");

Now when this line of code is executed it will redirects user to the your desired webpage. But what if you want delay? For example you want to display some msg and then want to redirect the user, following code is the solution for this problem, it will redirect user after some time delay.

header("refresh:2;url=yourdesiredpage.php");

The above code will redirect user after 2 seconds.

Sending query string from header function
You can also send query string from header function, here is the code for this 

header("location:yourdesiredpage.php?msg=somemessagehere");

Steps that must be in your mind while using header function

1) Try not to use head tag if you want to use header function to redirect the user. Just print message using echo and then redirect the user, there is no need for any html tag.

2) Do not print any thing before header function, it will give error in some cases, infact in some php versions less than 5.4

Suggestion
If you want to redirect user to any webpage after delay of 5 seconds so that a message should be also display to user then you just follow this code

header("refresh:2;url=yourdesiredpage.php");
echo "You are redirecting to another page";

Just you see above, you should use echo after header function, it avoids errors in all cases and also it will do job!!!!

2) Use meta tag to redirect the user or refresh the page



The above meta tag will redirect user to the page u want. http-equiv='refresh' will capable to redirect user using meta tag, content='5 means it will redirect after 5 seconds, url='yourdesiredpage.php' is the url where user will be redirected.

Note:- meta tag must be use inside head tag

Suggestion:- It is better to use header function to redirect the user instead of meta tag.






0 comments: