user2711681
user2711681

Reputation: 275

Php session security hardening

I would like to further harden my security of access the pages. What I have currently the very top of every page is this. Some articles suggest that this is not helpful $_SESSION['HTTP_USER_AGENT'] is that true ? I also call some pages by passing get values any best way to secure those input beside using mysql_real_escape_string ?

session_start(); 
if(!( isset($_SESSION['eID']) && !empty($_SESSION['eID']) && isset($_SESSION['uID']) && !empty($_SESSION['uID']) && isset($_SESSION['HTTP_USER_AGENT']) && !empty($_SESSION['HTTP_USER_AGENT']) ))
{

}
else
{
  //all other codes goes here.

}

Upvotes: 0

Views: 387

Answers (1)

ZeWaren
ZeWaren

Reputation: 4188

Checking for the existence of HTTP_USER_AGENT won't help you secure your sessions. Someone willing to compromise your website will forge one instantly.

AFAIK, the best way to secure a $_GET variable is:

  • Ensuring that it is present.
  • Checking that its type is correct (int, float, string, array, etc.)
  • Checking that the content is valid and allowed (example: positive for page numbers, without special characters for strings). For strings, you can use regular expressions.

Only then you should use mysql_real_escape_string.

Example:

if(!(isset($_GET['search'] && is_string($_GET['search']) && preg_match('/[a-zA-Z0-6 \-"\']/', $_GET['search']))) {
  die("Search was not set or is invalid");
}
do_some_query(mysql_real_escape_string($_GET['search']));

Also, you should not put this code at the top of all your pages, but instead put it in a function in another file and call it.

Example:

in sessions.php (don't put this file where it can be called directly):

function check_session() {
  session_start();
  if (isset($_SESSION['id']) && !empty($_SESSION['id'])) //Add more conditions here
    return true;
  return false;
}

in other files:

require_once(dirname(__FILE__)."/sessions.php");
if (!check_session()) {
    die("Forbidden"); //Or redirect to a login page
}

Upvotes: 1

Related Questions