Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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).

like image 317
redburn Avatar asked Jun 04 '11 21:06

redburn


3 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.)

like image 143
NikiC Avatar answered Nov 11 '22 16:11

NikiC


$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());
}
like image 3
Anze Jarni Avatar answered Nov 11 '22 16:11

Anze Jarni


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());
}
like image 3
kevinji Avatar answered Nov 11 '22 15:11

kevinji