Guides

Protection of PHP web pages using session variables

Examples of programming

Access to the pages of a website can be protected by scripts in the PHP language using session variables.

Once the script has been created in php (in the example check.php), it must be recalled in all the pages of the website we wish to protect (in our example, the page to be protected is unique and is inizia.php).

The example shown here uses four files:

The concept is quite simple: the login page checks whether or not the user is authorised to access by setting a session variable called authorised, which will be tested - thanks to the check.php - by all the pages involved in access control. The check is therefore made by inserting the check.php script in each page before the tag in other words before sending the page to the browser.

All the user names and passwords in the example are contained in a text file (pasx.txt) which, for reasons of simplicity, is not encrypted: in any case, it is possible to increase the level of security by encrypting both the user name and the password using, for example, MD5 encryption: http://www.php.net/manual/en/function.md5.php

Further protection can be introduced by placing the pasx.txt file in a dedicated folder, making it inaccessible to reading via the web. This last setting can be made in two ways:

  • via the web, using the control panel for Windows plans;
  • through a modification to the .htaccess file for Linux plans.

Obviously, the best solution is to store the access data in a database.

The contents of the pasx.txt file are as follows:

prova~:~prova
test~:~test
tentativo~:~tentativo

each line of the file contains a pair (user, passwd) separated by the special characters ~:~

The contents of the login.php file are as follows:

<?php
session_start();
if (isset($_POST["invio"])) {
  $puntatore = fopen("testi/pasx.txt", "r");
  $trovato = 0;
  while ((!feof($puntatore)) && (!$trovato)) {
    $linea = fgets($puntatore);
    $trovato = stristr($linea, $_POST["userid"]);
    $puntatore++;
  }
  fclose($puntatore);
  list($nomeutente, $password) = split("~:~", $linea);
  if (($trovato)  && ($_POST["passwd"] == trim($password))) {
    $_SESSION["autorizzato"] = 1;
    $destinazione = "inizia.php";
  } else {
    $destinazione = "destroy.php";
  }
  echo '<script language=javascript>document.location.href="'.$destinazione.'"</script>';
} else {
  // HTML ?>
  <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
  <html>
  <head>
  <title>Prova Login php</title>
  <meta name="Generator" content="EditPlus">
  <meta name="Author" content="">
  <meta name="Keywords" content="">
  <meta name="Description" content="">
  </head>
  <body>
  <form method=post action="login.php">
    <table width="300" cellpadding="4" cellspacing="1" border="0">
      <tr>
        <td colspan="2" align="left">
          <u>inserite nome utente e password</u>:
        </td>
      </tr>
      <tr>
        <td>
          nome utente: 
        </td>
        <td>
          <input type="text" name="userid">
        </td>
      </tr>
      <tr>
        <td>
          password: 
        </td>
        <td>
          <input type="password" name="passwd">
        </td>
      </tr>
      <tr>
        <td colspan="2">
          <input type="submit" name="invio" value="invio">
          &nbsp;&nbsp;
          <input type="reset" name="cancella" value="cancella">
        </td>
      </tr>
    </table>
    <br>
  </form>
  </body>
  </html>
<? //fine HTML
}
?>

The login.php script takes care of showing the user the data entry form (user and password) and checking that the values entered correspond to one of the pairs in the pasx.txt file. If the user is recognised authorised user), he script initialises both the session and the authorised, variable, directing the browser to the first protected page inizia.php; otherwise, (unauthorised user) the destroy.php script is called, it deletes all the contents of the open session and returns to the login page. For the session to work properly, it is very important that the login.php page contains the line at the start of the php code:

session_start(); 

The contents of the check.php file are as follows:

<?php
session_start();
if (!isset($_SESSION["autorizzato"])) {
  echo "<h1>Area riservata - accesso negato</h1>";
  die();
}
?>

Once the authorisedession variable has been activated, each page that includes the check.php script will be displayed without any problems, if the login was successful. If, however, the login is unsuccessful, an error message will be displayed.

All pages to be protected must contain this line of code, before the tag:

<?php
include("check.php"); 
?>

The session is terminated in two ways, by closing the browser or by calling the destroy.php script.

The contents of the destroy.php file are as follows:

<?php
session_start();
session_unset();
session_destroy();
?>
<script language="JavaScript">
document.location.href = "login.php"
</script>

Obviously, the scripts shown in this brief example are not complete if they are not integrated with the pages of the website to be protected. In our example, therefore, we integrate the scripts seen so far with the content of the page to be protected inizia.php. he integration is carried out by inserting first of all in the HTML code, the call to the check.php script that tests whether or not the user is authorised to access.

<? include("check.php"); ?>
<!doctype html public "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title> Pagina di test - PHP login </title>
<meta name="Generator" content="EditPlus">
<meta name="Author" content="">
<meta name="Keywords" content="">
<meta name="Description" content="">
</head>
<body>
Esempio: login effettuato con successo
</body>
</html>