something interesting about header Location

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
jazz090
Forum Contributor
Posts: 176
Joined: Sun Apr 12, 2009 3:29 pm
Location: England

something interesting about header Location

Post 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?
Defiline
Forum Commoner
Posts: 59
Joined: Tue May 05, 2009 5:34 pm

Re: something interesting about header Location

Post 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
?>
User avatar
jazz090
Forum Contributor
Posts: 176
Joined: Sun Apr 12, 2009 3:29 pm
Location: England

Re: something interesting about header Location

Post 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?
Defiline
Forum Commoner
Posts: 59
Joined: Tue May 05, 2009 5:34 pm

Re: something interesting about header Location

Post 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).
User avatar
jazz090
Forum Contributor
Posts: 176
Joined: Sun Apr 12, 2009 3:29 pm
Location: England

Re: something interesting about header Location

Post by jazz090 »

yes, thank you for that :D
mickd
Forum Contributor
Posts: 397
Joined: Tue Jun 21, 2005 9:05 am
Location: Australia

Re: something interesting about header Location

Post by mickd »

Most the time after i use a header redirect, i just use die to stop the rest of the script.
User avatar
jazz090
Forum Contributor
Posts: 176
Joined: Sun Apr 12, 2009 3:29 pm
Location: England

Re: something interesting about header Location

Post by jazz090 »

yes thats a good point, thank you
Post Reply