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).
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());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With