For each page that you want to protect with this access controlscheme (so that only registered users may view it), your script mustfollow the procedure described by the flowchart below.
The first time that a protected page is requested, the user will nothave entered his or her login details yet. The script detects this andprompts the user for a username and password with a login form insteadof displaying the requested page. When that form is submitted, the pageis reloaded, this time with a username and password specified. Thescript sees that the login details have been specified, and registersthem as session variables so that they remain available for the rest ofthe user's visit. Finally, the script checks the database to make surethe username/password combination is valid. If it is, the page requestedis displayed. If not, an "access denied" message is displayed with alink inviting the user to try logging in again.
Since this procedure will be identical for all protected pages, itmakes sense to implement it as a common include file. This will allowyou to protect a page by simply adding the following line at the top ofthe file:
<?php include 'accesscontrol.php'; ?>
With the objective now clear, I'll walk you through the code for accesscontrol.php.Begin by including your two handy include files:
I use include_once here instead of include just in case the main file also uses these include files. If common.php were included twice, for example, PHP would issue a warning that the error function had been declared twice.
Next, I call session_start to either begin a new session(if this is the first page in the user's visit), or load the variablesbelonging to the user's current session.
session_start();
At this point, the user's login details should be available whetherthey were just submitted from a login form (in the $_POST array) or stored in the user's session (in the $_SESSION array). So as a first order of business, the script needs to pull thelogin credentials out of either the $_POST or the $_SESSION array:
These two lines use a handy (if confusing) syntax called the ternaryoperator, which takes this form:
condition ? value_if_true : value_if_false
If condition is true, the expression will equalvalue_if_true. If not, it will equal value_if_false.
So if you compare this to the first line above, you'll see that ifthere is a 'uid' value in the $_POST array (isset($_POST['uid'])),$uid will be set to the value of $_POST['uid'].If not, it will be set to the value of $_SESSION['uid'].The same thing happens to create $pwd from the $_POST or $_SESSION array.
If you really aren't comfortable with the ternary operator, here'show you can do the same thing with if statements:
As you can see, the ternary operator can save a lot of typing if youcan get your head around it!
Now, at this stage, the only case in which the user's ID and passwordwould not be available is if they had not been entered during thisvisit to the site.