I want to redirect the page by using tag i开发者_运维技巧n the header, but it's not working.
At the top of your page add the following (before any html or php):
<?php
header('Location: http://stackoverflow.com/users/300204/zaf');
exit();
?>
If that redirects you (to the homepage of an awesome programmer) then you need to check that you have not output any content before using this header() function. The header() function needs to be called before ANY content is sent to the user.
Most usual reason of this is "headers already sent" error. Thus, you have 2 problems to solve.
From absence of error message text in your question, I can assume you don't have this text. But it is necessary for the programmer to see every error message occurred. You have to turn
display_errors
settingon
in the developer's environment or peek logs in the production. Also,error_reporting()
level must be set to E_ALL.Application design. Your application must be divided into 2 parts: business logic and presentation logic. First one getting data from the user, from the database, etc.etc. Latter one displays gathered data. Not a single byte must be sent to the browser before presentation logic part get to run. In this case you'll never have such an error.
One exception is BOM - Byte Order Mark, a symbol, being put into your files silently by some editors. Just use "Save without BOM" feature.
You need:
header('Location: http://google.com');
It might not work because you have some php output before the header make sure there are no empty spaces or any characters, or ECHOs outputted before the headers function. Usually it will give an error and you can located where you have this extra space something like "Headers already sent by page on line 1 in index.php"
As some have pointed out, you have to output headers before content. The ideal way to do this is to separate your business logic and presentation logic into different parts, but sometimes you're stuck with legacy code that doesn't do this.
In this situation, PHP's output control functions can be useful; use ob_start() and ob_end_flush() to capture your output then flush it at the end. This allows your code use header() more or less anywhere, e.g.
<?php
function doSomeStuff() {
echo 'look, outputting stuff here';
header('Location: /');
}
doSomeStuff();
?>
The above code will give you the error about headers already being sent, but the following code will work.
<?php
function doSomeStuff() {
echo 'look, outputting stuff here';
header('Location: /');
}
ob_start();
doSomeStuff();
ob_end_flush();
?>
In this case, the output from echo() is not sent until ob_end_flush(), so the header() call works correctly. This approach can be used to wrap legacy code that doesn't properly separate business and presentation logic.
精彩评论