Page 1 of 1
something interesting about header Location
Posted: Sun May 10, 2009 5:10 am
by jazz090
i came across something interesting today, i ran some code and i called the header location and on the line after i ran a mysql query,
here is whats interesting: the page was relocated and the query was also executed:
Code: Select all
header("Location: somewhere.php");
mysql_query("mysql syntax");
how is this even possible? which begs the question: after you execute header location, does the rest of the script continue to get executed?
Re: something interesting about header Location
Posted: Sun May 10, 2009 5:15 am
by Defiline
It is corrert.
The headers will be sent only if your script has finished executing.
If you have a syntax error script will never be executed even if you have a mistaka after header();
Code: Select all
<?php
header('Location ... ');
// Here we are doing something
file_put_contents(...);
mysql_query()...
// Now we are being redirected
?>
Re: something interesting about header Location
Posted: Sun May 10, 2009 5:18 am
by jazz090
so what you are saying is: once the script has finished executing, i.e. once all code has been executed, php then applies all headers which we have specified so even if i have a mysql query or whatever, all of them are executed before any headers are sent?
Re: something interesting about header Location
Posted: Sun May 10, 2009 5:24 am
by Defiline
Yes.
The thing you should never do is to flush any content.
If you have flushed something in your script, headers will not be executed.
In this cate you must use buffering (ob_start and ob_get_contents).
Re: something interesting about header Location
Posted: Sun May 10, 2009 5:27 am
by jazz090
yes, thank you for that

Re: something interesting about header Location
Posted: Sun May 10, 2009 7:00 am
by mickd
Most the time after i use a header redirect, i just use
die to stop the rest of the script.
Re: something interesting about header Location
Posted: Sun May 10, 2009 9:16 am
by jazz090
yes thats a good point, thank you