An error is reported when you run the following code.
<?phpsession_start();if(!isset($_SESSION['user']) || null === $_SESSION['user']){ header('location:login.php'); exit;}?>
Error message:
Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at D:\PHPProjects\agilelite\index.php:1) in D:\PHPProjects\agilelite\index.php on line 2Warning: Cannot modify header information - headers already sent by (output started at D:\PHPProjects\agilelite\index.php:1) in D:\PHPProjects\agilelite\index.php on line 6
To solve this problem, study the use of the exit function.
Return, break, and contiue are language structures, just like if statements, but exit is a function. The exit function is used to output a message and terminate the current script.
If a piece of text contains multiple? ?> To exit the current script.
For example, if a php text includes the code, the output is NowaMagic.
<?phpecho "Hello";exit;?><?phpecho "NowaMagic";?>
The syntax format of the exit function is as follows (void indicates no return value ):
void exit ([ string $status ] )void exit ( int $status )
If status is a string, this function prints status before the script exits.
If status is an integer, the integer is used as the exit status. The exit status should be from 0 to 254. Exit status 255 is retained and disabled by PHP. Status 0 is used to indicate successful termination of the program.
Use exit after the header jump
The PHP header can output http header information, provided that no content can be output before the header, because all content is output to the client as the http body. Once there is body content, it is impossible to add any header information.
A common method of the header function is to perform redirection and redirect.
For example, if I want to go to an address, I only need to execute the following code:
<?phpheader('Location: http://www.bkjia.com/');?>
The browser will receive an http status code of 302, telling him that the content has been transferred.
It is important that php will continue to execute the following code after calling the header function. You can use my code to test it in person:
<?phpheader('Location: http://www.bkjia.com/');$fp= fopen('header.txt', 'w+');fwrite($fp, date('Y-m-d H:i:s'));?>
The header.txt file will be opened and the time will be checked if the fwrite.pdf is executed!
In this regard, the solution is to add exit after each header function to ensure that the current page is stopped, and then turn to the address specified by location.
To avoid exit everywhere, you can write a function specifically used for steering, such:
<?phpfunction DoRedirect($strUrl) {header('Location: ' . $strUrl);exit;}?>
In addition, to avoid outputting the body content before the header, many php frameworks use php at the end of the page without writing?> Because some people are always used to?> Adding a line feed later is really a bad habit.