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

How to Create an HTML Form Linked with MySQL Database in PHP

If you're looking for example code and detailed discussion on how to create an HTML form that stores data in a MySQL database using PHP then this post might be what you're looking for. I assume that you're familiar with basic HTML, CSS, PHP coding, and  MySQL. I am going to divide this small project into two parts: The HTML form itself that takes input from the user and the PHP script that saves it into the database A table that displays the user-added data that has been saved in the database. We'll be dealing with the first part in this tutorial. Again I'd like to break this problem into a few parts so that it's easier for you to understand and probably gives you an insight into how breaking up a problem into smaller chunks can help make things clearer in your mind. Let's think about it, there is an HTML form (that is HTML code), then there is the PHP code that deals with the user-input data, and the MySQL database itself. For this tutorial, we'll b