Forum Moderators: coopster
When certain pages within my website are accessed I would like it to check to see if the user is logged in. If they are not I want it to redirect to the login page. If they are display a list of options (admin center, my profile, etc).
Here is the code i'm trying to use:
<?
if(!$session->logged_in){
header('Location: http://www.mydomain.com/main.php');
exit();
}
else
{
echo "Welcome <b>$session->username</b>, you are logged in. <br>"
."[<a href=\"userinfo.php?user=$session->username\">My Account</a>] "
."[<a href=\"useredit.php\">Edit Account</a>] ";
if($session->isAdmin()){
echo "[<a href=\"admin/admin.php\">Admin Center</a>] ";
}
echo "[<a href=\"process.php\">Logout</a>]";
}
?>
The error that displays is:
Warning: Cannot modify header information - headers already sent by (output started at /home/name/public_html/domain.com/trip.php:1) in /home/name/public_html/domain.com/trip.php on line 7
(line 7 is the if line)
Any help would be greatly appreciated. Thanks!
make sure headers haven't been sent before you try and send again. I use a function called transport,
function transport($GoTo){
//see if headers have been sent
if(!headers_sent()){
//send them with location - ruby style
header('Location: '.$GoTo);
} else {
//fall back to the js version
echo "<script type=\"text/javascript\">";
echo "window.location = \"$GoTo\"";
echo "</script>";
}
}
if(!$session->logged_in){
transport("http://www.mydomain.com/main.php");
# make sure we die, so if no JS they dont see our page!
die;
}
else
{
echo "Welcome <b>$session->username</b>, you are logged in. <br>"
."[<a href=\"userinfo.php?user=$session->username\">My Account</a>] "
."[<a href=\"useredit.php\">Edit Account</a>] ";
if($session->isAdmin()){
echo "[<a href=\"admin/admin.php\">Admin Center</a>] ";
}
echo "[<a href=\"process.php\">Logout</a>]";
}
but you want to try and avoid using JS redirects, as if they have JS enabled it will fail. So add your login test before you send headers.
Alan