The purpose of this code, is to disconnect from a database and then redirect to a new permanent address:
mysql_close($con);
header("HTTP/1.1 301 Moved Permanently");
header('Location: http://www.example.com/');
exit();
Instead of redirecting, though, it just displays a blank page.
However, if I move the line mysql_close($con);
down under the header functions, the code does succeed in redirecting:
header( "HTTP/1.1 301 Moved Permanently" );
header('Location: http://www.example.com/');
mysql_close($con);
exit();
- Why does putting
mysql_close($con);
before the header functions prevent the redirect? - Will
mysql_close($con);
still be executed in the 2nd arrangement?
UPDATE
To help those that come across this later. Here is the answer to my question.
Answer 1: The reason putting mysql_close($con);
before the header functions prevented the redirect, was because the connection was already closed. And, instead of doing the most sensible thing (silently accepting this fact), PHP threw an error that prevented the redirect from happening.
Answer 2: Yes, the code after the redirect does get executed in the 2nd arrangement.
To close the connection only if its open, you can use is_resource:
if (is_resource($con))
{
mysql_close($con);
}
header( "HTTP/1.1 301 Moved Permanently" );
header('Location: http://www.example.com/');
exit();
Lastly, here's a function that will close the connection without throwing an error if the connection is already closed:
function mysql_close_with_no_backtalk($con)
{
if (is_resource($con))
{
mysql_close($con);
}
}
So, using the function above, my edit looked like this:
mysql_close_with_no_backtalk($con);
header( "HTTP/1.1 301 Moved Permanently" );
header('Location: http://www.example.com/');
exit();