I have a little problem with PHP, probably for most of you it’s a stupid problem, but I need your help.
Here’s my code:
function is_logged() {
if(isset($_COOKIE['username'])) {
return true;
} else {
return false;
}
}
And here is a piece of the whole code where I need to deny someone the access if isn’t logged.
if(!is_logged()) {
header("Location: ./?act=Home");
}
Where do I made the mistake?
EDIT: I’m sorry, I haven’t explained the problem at all… This function does not redirect, leaving blank the page!
Try this:
At the very beginning of the page, put
ob_start()to prevent any error messages from being outputted, and then change the check to this:The
die()here prevents the PHP from doing something else (perhaps modifying the header so there is no redirect). You should also check to see if there is an error message being generated before this code is called (as this is usually the problem withheader()redirects). Make sure error messages are turned on in php.ini and/or in your PHP with display_errors. Note thatob_startandob_cleanwill prevent error messages from showing up, so you will want to temporarily remove them to see what the errors are….That all being said, just using cookies to determine if a user is logged in or not is considered bad practice, as it is incredibly easy for anyone to make a cookie on their browser. You should being doing some server-side check to make sure it is a valid login.