Skip to main content

Implementing User Authorization Using Session Control

Implementing User Authorization Using Session Control

You may want to read An Example of User Authentication System in PHP, What is Session Control/Variables? before reading this post.

In this post we are going to create a ‘secret’ site whose pages will only be accessible after logging in using the correct username and password. We will be using our knowledge of Session Control/Variables since we want authorization for the whole site and not a single page.

The site that we are going to create will have three ‘secret’ pages plus one-one page for logging in and homepage.

Let’s start by having a look at the login page code:

<html>
<head>
<title>My Web Site | Login</title>
</head>

<body>
<h1>My Web Site</h1>
<h2>Login </h2>
<?php
define
('USERNAME','happyjoe');
define('PASSWORD','123456');

//if submit button was pressed
//that means form was submitted
if(isset($_POST['submit']))
{
    
//fetch other form data
    
$username=$_POST['username'];
    
$password=$_POST['password'];
    
    
//start a session
    
session_start();

    
//match username & password
    
if($username==USERNAME && $password==PASSWORD)
    {
        
//save session variable with the username
        //which will be unique
        
$_SESSION['user']=$username;
        
//redirect to homepage
        
header("Location: home.php");
    }
    else
        echo 
"<p style=\"color:#ff0000;\">Incorrect 
    Username/Password. Please Try Again.</p>"
;
}
else
//requesting the login page
{
    
//if requesting the login page
    //check if already logged in
    //and redirect to homepage if true

    //start session
    
session_start();
    if(isset(
$_SESSION['user']))
    {
        
//redirect to homepage
        //if already logged in
        
header("Location: home.php");
    }
}
//if not logged in show the login page
?>
<form name="form1" id="form1" method="post" action="">
  <table width="30%" border="0" cellspacing="0" cellpadding="0">
    <tr> 
      <td>Username</td>
      <td><input name="username" type="text" id="username" /></td>
    </tr>
    <tr> 
      <td>Password</td>
      <td><input name="password" type="password" id="password" /></td>
    </tr>
    <tr>
      <td>&nbsp;</td>
      <td><input name="submit" type="submit" id="submit" 
    value="Submit" /></td>
    </tr>
  </table>
</form>
</body>
</html>

Now the homepage:

<html>
<head>
<title>My Web Site | Login</title>
</head>

<body>
<h1>My Web Site</h1>
<?php
//start session again
session_start();
//if someone is requesting this page
//without logging in
if(!isset($_SESSION['user']))
{
    echo 
"<p>You are not Authorized to view this page. Please <a href=\"login.php\">Login</a> first.</p>";
    
//exit script; don't execute any further
    
exit;
}
//if logged in
?>
<h2>Secret Pages </h2>
<ul>
  <li><a href="page1.php">Page1</a></li>
  <li><a href="page2.php">Page2</a></li>
  <li><a href="page3.php">Page3</a></li>
</ul>
<?php
//show user name at the bottom
echo "<p>USER: <i>".$_SESSION['user']."</i></p>";

?>
</body>
</html>

You can see that the content of the homepage will only be accessible when the session variable has been set by successful login from the login page.

The homepage after login will look something like below:

Home Pag after loggin in

As you can see there are three links to the bottom. The codes for these pages are listed below:

For page one:

<html>
<head>
<title>My Web Site | Page1</title>
</head>

<body>
<h1>My Web Site</h1>
<?php
//if someone is requesting this page
//without logging in
session_start();
if(!isset(
$_SESSION['user']))
{
    echo 
"<p>You are not Authorized to view this page. 

Please <a href=\"login.php\">Login</a> first.</p>";
    
//exit script; don't execute any further
    
exit;
}
//if logged in
?>
<h2>Page1</h2>
<p>this is a secret page.</p>
</body>
</html>

For page two:

<html>
<head>
<title>My Web Site | Page2</title>
</head>

<body>
<h1>My Web Site</h1>
<?php
//if someone is requesting this page
//without logging in
session_start();
if(!isset(
$_SESSION['user']))
{
    echo 
"<p>You are not Authorized to view this page. 

Please <a href=\"login.php\">Login</a> first.</p>";
    
//exit script; don't execute any further
    
exit;
}
//if logged in
?>
<h2>Page2</h2>
<p>this is a secret page.</p>
</body>
</html>

For page three:

<html>
<head>
<title>My Web Site | Page3</title>
</head>

<body>
<h1>My Web Site</h1>
<?php
//if someone is requesting this page
//without logging in
session_start();
if(!isset(
$_SESSION['user']))
{
    echo 
"<p>You are not Authorized to view this page. 

Please <a href=\"login.php\">Login</a> first.</p>";
    
//exit script; don't execute any further
    
exit;
}
//if logged in
?>
<h2>Page3</h2>
<p>this is a secret page.</p>
</body>
</html>

If you look closely, each ‘secret’ page checks to see if the session variable is set or not (which can only be after successful login). So, even direct access to these pages is restricted.

In case someone tries to access these pages directly without logging in, he/she would see:

It'd look like this when anyone tries to access this page without loggin in


We could have created the whole site using the method outlined in the post How does CMS Create Dynamic Pages to create the whole site off just one script but I wanted to illustrate the fact that session variables are accessible from different pages too, across a session.

Previous Articles:

Popular posts from this blog

Fix For Toshiba Satellite "RTC Battery is Low" Error (with Pictures)

RTC Battery is Low Error on a Toshiba Satellite laptop "RTC Battery is Low..." An error message flashing while you try to boot your laptop is enough to panic many people. But worry not! "RTC Battery" stands for Real-Time Clock battery which almost all laptops and PCs have on their motherboard to power the clock and sometimes to also keep the CMOS settings from getting erased while the system is switched off.  It is not uncommon for these batteries to last for years before requiring a replacement as the clock consumes very less power. And contrary to what some people tell you - they are not rechargeable or getting charged while your computer or laptop is running. In this article, we'll learn everything about RTC batteries and how to fix the error on your Toshiba Satellite laptop. What is an RTC Battery? RTC or CMOS batteries are small coin-shaped lithium batteries with a 3-volts output. Most laptops use

The Best Way(s) to Comment out PHP/HTML Code

PHP supports various styles of comments. Please check the following example: <?php // Single line comment code (); # Single line Comment code2 (); /* Multi Line comment code(); The code inside doesn't run */ // /* This doesn NOT start a multi-line comment block /* Multi line comment block The following line still ends the multi-line comment block //*/ The " # " comment style, though, is rarely used. Do note, in the example, that anything (even a multi-block comment /* ) after a " // " or " # " is a comment, and /* */ around any single-line comment overrides it. This information will come in handy when we learn about some neat tricks next. Comment out PHP Code Blocks Check the following code <?php //* Toggle line if ( 1 ) {      // } else {      // } //*/ //* Toggle line if ( 2 ) {      // } else {      // } //*/ Now see how easy it is to toggle a part of PHP code by just removing or adding a single " / " from th

Pong Game in HTML & JavaScript (Updated)

HTML Pong Game Gameplay Pong is one of the first games that many people from the 80s or 90s had played as children. Lots of people know it as a simple arcade game but what they probably do not know is that this simple game helped establish the video game industry! In this post, we'll be making our version of a very simple but fully working Pong game in HTML, CSS and JavaScript. Basic Game Structure Games, however simple or complex they may be, follow the basic Game Loop design as shown in the chart below. Event-oriented game engines usually encapsulate the design and provide you with an event mechanism for handling various parts like the input, update, and rendering but internally the basic design is being followed. Pong Game Loop For our Game Loop, we'll be using JavaScript setInterval so that the game code remains asynchronous and separate. As you may have guessed a while (or any other loop) will freeze the page. For our input, we'll be using onmousemove event to update t