Restricting Access To Your Sites Pages
So now that we have the ability to register and login users, how do we allow those users in and keep others out? Lets create a simple HTML page with the following PHP code at the top.
File: account.php
<?php
require_once('common.inc.php');
restrictAuth();
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Restricted Users Area</title>
</head>
<body>
<center>
<h1>Hello, <?php echo $auth['first_name']; ?> and welcome to the users area.</h1>
<div>
Only Authenticated users can see this content. Hurray or you!
</div>
<div>
<a href="logout.php">Logout!</a>
</div>
</center>
</body>
</html>
By including the common.inc.php file we can call the restictAuth() function which will redirect any attempts from non authenticated users to the login page. Only if the user has an authenticated session will they be allowed to view the content on this page. The neat thing about this is, no matter what page you include this code in, when the user is redirected to the login page and then successfully authenticates, they will be redirected back to the page they originally wanted!