Here is my index.php
<?php
session_start();
if($_SESSION['authorizedreferral'] == false){ //login.php sets 'authorizedreferral' to false, and redirects to here. That way, login.php can't be accessed directly.
session_destroy(); //destroy the session, so the 'authorizedreferral' session is revaluated each time.
echo "<h1>No ticky, no washy!</h1>"; //Sorry, don't pass go, and don't collect $200
}elseif(!isset($_COOKIE['loggedin'])){ //if there isn't a 'loggedin' cookie set, forward to the login.php page
$_SESSION['authorizedreferral'] = true; //yes, this is a correct referral. Otherwise, login.php will kick you out!
header("Location: login.php"); //forward to login.php
exit; //need this for some reason?
}
?>
Here is login.php:
<?php
session_start(); //start the session
if(!isset($_SESSION['authorizedreferral'])){ //if 'authorizedreferral' isn't set (i.e. someone just loads login.php directly)
$_SESSION['authorizedreferral'] = false; //set 'authorizedreferral' to false - they aren't allowed here!
header('Location: http://'.$_SERVER["HTTP_HOST"]); //and ship 'em back home!
exit; //need this for some reason
}
?>
Here are the possible situations:
- User goes to index.php – since they haven’t logged in (don’t have login cookie), they get sent to the login.php page to login.
- User tries to access login.php directly – they are sent back to the index.php, and get the message “No Ticky, no washy!”
However, right now, the user always receives “No Ticky, No Washy!” when accessing the index.php page. What am I missing?
The first time the user comes to the site, they’ll have an empty session. Your first if() clause will always evaluate to true, because of PHP’s typecasting rules:
The session is empty, so there is no authorizedreferal value in the session, so PHP returns a ‘null’ (and an unset array key warning). Under PHP’s typecasting rules,
null == falseis TRUE.You’ll have to change your logic to check if a user’s logged in (do NOT store that in the cookie – store it in the session), and redirect to the login page:
The other alternative is to use the strict comparison operator:
which would only succeed if there really WAS an authorizedreferral value that was set to boolean true. You’d still get the unset array warning for brand new users, though.