Re: header("Location:...") fails

From: Date: Wed, 13 Jan 2010 21:02:59 +0000
Subject: Re: header("Location:...") fails
References: 1 2  Groups: php.general 
Request: Send a blank email to php-general+get-301082@lists.php.net to get a copy of this message
Paul M Foster wrote:
On Wed, Jan 13, 2010 at 11:39:18AM -0800, Richard S. Crawford wrote:
Here is a snippet of code that is going to be the death of me: ------------------------------------------------------------ // Create a new project $projectcode = strtoupper(addslashes($_POST['projectcode'])); // project code // Make sure the project code is unique if (!$existingproject = mysql_query("select * from pb_versions where projectcode like '".strtoupper($projectcode)."'")) {
    die ("Could not check for existing project code!<br />".mysql_error());
} $numprojects = mysql_num_rows($existingproject); if ($numprojects > 0) {
    $pid = mysql_result($existingproject,0,"versionID");
    header("Location:managebudget.php?e=1&pid=$pid");
} ------------------------------------------------------------ Now, even if $numprojects is 1, 2, 3, etc., the header() command is not executed. Strangely, a header("Location") command later on in the script *is* executed. I've output the value of $numprojects, so I know that it's greater than 0, so the command header("Location:managebudget.php?e=1&pid=$pid"); *should* be executed... but it isn't. (Weirdly, if I put a die() command *after* this header() command, it works... but it seems pathologically inelegant to do so.) Obviously, I'm missing something incredibly basic. Can anyone help me figure this out?
For one thing, I'd put a space after "Location:" in the header() call. But I've found that this call will sometimes fail (or *look* like it fails) unless you put something like exit(); after it. This terminates execution and forces the script to transfer control as it should. Just make it a habit to always include and exit(); call after your final header() call.
Just make your life easy and create a redirect() function that generates the header instruction, makes a relative URL into an absolute URL and does the exit call. Then you just need to do: redirect( 'target.php' ); Sooooooooo much simpler :) Cheers, Rob. -- http://www.interjinn.com Application and Templating Framework for PHP

« previous php.general (#301082) next »