Tuesday, August 30, 2011

[ PHP CASE ] header() not redirecting you to the specified location ?

It's an infrequent case if you be a PHP Developer or at least a web developer and  not using header() function for redirecting the user to a specific location .
 
Let me refer you to PHP Documentation page and check out what is header() and it's purpose .
Ok as you can see, here's is it's prototype :

void header ( string $string [, bool $replace = true [, int $http_response_code ]] )

In the simplest form, header() could be use to send the web page visitor to a specific location .


here's an example :

<?php
         header("location:register.php");
?>

In this case, the php interpreter will redirect the visitor to the register.php page on the same website .
Q : I used header() function in my php code, but it did no response to me and nothing special happend in case of page rediction, what is the problem ?

A : While you are running PHP code and would like to use redirect() function, you should notice that in the block that you would like to redirect the visitor to the another page, you should not use any echo, print or any function for writing something on the web page before using header() function .

Let me explain it in more obvious manner .

suppose you written this code :

<?php
 echo "I want to redirect you to another page ...!";
 header("location:test.php");
?>

When you run up this snippet, you will not redirect to anywhere . This is because you used echo function before redirect() function .

If you would like to fix that code it's better to delete echo function or put it after redirect() function .

Here was one of the situations that might causes your code not to working properly.

regards,
-Arash

No comments:

Post a Comment