Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php header Location immediately?

Why the Location header does not redirect the page immediately? It always performs the entire process before redirecting?

I will give some example:

header('Location:http://www.php.net');
$f = fopen('demo.txt','w+');
fwrite($f,'Test');
fclose($f);

It always generates the TXT file before redirecting to http://www.php.net.

like image 966
Lelis Avatar asked Dec 12 '22 10:12

Lelis


2 Answers

Well, header() just sends certain header to browser. PHP still continues running the script after that. If you don't want to stop running the script, just use die; or exit; - it will stop processing the script further.

like image 64
Konrad Borowski Avatar answered Dec 23 '22 20:12

Konrad Borowski


It's because the header() function does not redirect, it sends a header. A browser may (theoretically) completely ignore it and choose to continue parsing the page. If you wish the script to not process after sending the header, fire die() or exit() immediately after.

like image 41
Madara's Ghost Avatar answered Dec 23 '22 21:12

Madara's Ghost