Home » Php » php – Multiple instances of header() + die() in single code line

php – Multiple instances of header() + die() in single code line

Posted by: admin July 12, 2020 Leave a comment


I’m trying to manipulate a PHP script so that it redirects to a particular URL instead of giving me a MySQL error. So I went from this…

$qs = mysql_query("SELECT url FROM $table WHERE `id` = $gid;") or die('MySQL error: '.mysql_error());

…to this:

$qs = mysql_query("SELECT url FROM $table WHERE `id` = $gid;") or header("Location: http://www.example.com");

Which works, but there are two things that concern me. Firstly, it defaults to a 302 redirect, and I would prefer a 301 redirect. Secondly, I’m worried that by removing die() from this line, the script isn’t properly exiting after the redirect.

Now, I’ve done a bit of homework here, but I can’t quite figure out if it’s possible to combine die() with two instances of header() in that single line of code (i.e. without changing what’s around this particular line).

How to&Answers:

In addition to the “You shouldn’t do this” notes, here’s how you could do it:

$qs = mysql_query(...) or (header(...) xor die);

Explanation: xor is just like or with the difference that it is guaranteed that the expressions on both sides get evaluated and are not short circuited. (Okay, xor is something different from or, but for the purpose of this answer that doesn’t matter.)


$query_string = '';
$location = '';

$qr = mysql_query($query_string);
if (!$qr) {
  header ('HTTP/1.1 301 Moved Permanently');
  header ('Location: '.$location);
  die('MySQL error: '.mysql_error());


You could use an if block:

$qs = mysql_query("SELECT url FROM $table WHERE `id` = $gid;");
if (!$qs) {
    header("Location: http://www.example.com");
    die('MySQL error: '.mysql_error());


You could always:

$qs = mysql_query("blah");
if (!$qs) {
   header('Location: blah');
   die('MySQL error: '.mysql_error());


There is no purpose to having the die message show up since any browser would catch the HTTP status code and act accordingly while ignoring the content of the document. There you should be using the exit() command which does the same thing minus echo’ing anything to the buffer.

You may be using this fallback operation so why not just make it a common fallback function:

function fallback($location='/default/path/to/somewhere') {
    header('HTTP/1.1 301 Moved Permanently');
    header('Location: '.$location);

$query = mysql_query('...') or fallback('/path/to/somewhere/');