Forum Moderators: coopster

Message Too Old, No Replies

Issue with redirecting user that is not logged in.

         

ThePr0fess0r

1:21 pm on Aug 7, 2009 (gmt 0)

10+ Year Member



Hello, I am new to PHP and am trying to get my website pages to check to see if the user has logged in.

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>] &nbsp;&nbsp;"
."[<a href=\"useredit.php\">Edit Account</a>] &nbsp;&nbsp;";
if($session->isAdmin()){
echo "[<a href=\"admin/admin.php\">Admin Center</a>] &nbsp;&nbsp;";
}
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!

Kings on steeds

1:45 pm on Aug 7, 2009 (gmt 0)

10+ Year Member



The problem is that php has already received a header (maybe you have echoed content to the page already so it has sent a content-type header?)

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>] &nbsp;&nbsp;"
."[<a href=\"useredit.php\">Edit Account</a>] &nbsp;&nbsp;";
if($session->isAdmin()){
echo "[<a href=\"admin/admin.php\">Admin Center</a>] &nbsp;&nbsp;";
}
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

ThePr0fess0r

2:48 pm on Aug 7, 2009 (gmt 0)

10+ Year Member



Ok, thank you very much! That worked to a point...if I am not logged in and try to access that page it takes me to the login screen just like it should. But, the problem I am running into now is that even if I am logged in it takes me to the login page.