Redirect page to root path
I have this class and what they need to do, if checking something is false, then the user will be redirected to the root domain path. but it doesn't work. here is the class
class security {
function checkAuth() {
if(isset($_COOKIE['AUTHID'])) {
$cookie = $this->secure($_COOKIE['AUTHID']);
$query = mysql_query("select username,password,active from tbl_users where password = '$cookie'") or die(mysql_error());
while($row = mysql_fetch_assoc($query)) {
//check if cookie is set
if(!isset($_COOKIE['AUTHID'])) {
header("Location: ".realpath($_SERVER['HTTP_HOST']));
}
//check if user is active
if($cookie == $row['password']) {
if($row['active'] == '0') {
setcookie("AUTHID","",time() - 100000);
header("Location: ".realpath($_SERVER['HTTP_HOST']));
}
else { //user is active
}
}
//check if hash in cookie matches hash in db
if($cookie != $row['password']) {
setcookie("AUTHID","",time() - 100000);
header("Location: ".realpath($_SERVER['HTTP_HOST']));
}
}
}
}
}
?>
- I don't think it's a good idea to redirect / output directly in a class for many reasons, the most important thing is that it defies the whole OO point. Rather, return false and call your script redirect.
- You need to send the headers as the FIRST thing you do, the header based redirect won't work if PHP starts to output the text, since the headers have already been sent.
Try
$_SERVER['SCRIPT_URI'];
or
"http://" . $_SERVER['HTTP_HOST'];
And, yes, exit (); after sending this header.
Remember to send the appropriate 30x header response code to redirect
a source to share
From PHP doc :
'HTTP_HOST': Content of the Host: header from the current request, if any.
It seems to me that this is the value sent from the client's browser, and since the client can change the request headers, I think it is better to use SERVER_NAME:
'SERVER_NAME' The hostname of the server under which the current script is being executed. If the script is running on a virtual host, this will be the value defined for that virtual host.
I think the correct way to do it is:
header("Location: http://{$_SERVER['SERVER_NAME']}/");
die();
Comment to "Location: /"
As stated in the Definitions of Redirect Header Fields via Location Header must be specified with an absolute URI, including http://www.servername.com/redirect/to/this/resource.html , not just / redirect / to / this / resource. html. (But it works by redirecting to /, but that's not 100% correct).
a source to share
The function works on the file system and returns the path to the canonicalized absolute file system. realpath
But you need a URI. So try this:
header("Location: http://".$_SERVER['HTTP_HOST']."/");
exit;
a source to share