Skip to content

Instantly share code, notes, and snippets.

@cballou
Created March 25, 2012 14:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save cballou/2196124 to your computer and use it in GitHub Desktop.
Save cballou/2196124 to your computer and use it in GitHub Desktop.
Securing Your PHP Sessions - Helpers
<?php
// sample IP
$ip = '192.168.1.100';
/**
* Trims the IP address and returns it in the
* format XXX.XXX.XXX.0
*/
function trimIP($ip) {
$pos = strrpos($ip, '.');
if ($pos !== false) {
$ip = substr($ip, 0, $pos+1);
}
return $ip . '.0';
}
$ip = trimIP($ip);
<?php
// assumes you have set the session variable logged_in to a boolean value depending on login status
if (!isset($_SESSION['logged_in']) || $_SESSION['logged_in'] == false) {
// get_ip_address() can be found on another post referenced in this article
$_SESSION['ip_address'] = get_ip_address();
} else {
if ($_SESSION['ip_address'] !== get_ip_address()) {
// destroy
session_destroy();
$_SESSION = array();
if (!headers_sent()) {
// set a flash and redirect to the login page
header('Status: 200');
header('Location: ' . urlencode('/login'));
exit;
} else {
// throw an error message
exit;
}
}
}
<?php
// assumes you have set the session variable logged_in to a boolean value depending on login status
if (!isset($_SESSION['logged_in']) || $_SESSION['logged_in'] == false) {
$_SESSION['user_agent'] = (isset($_SERVER['HTTP_USER_AGENT'])) ? $_SERVER['HTTP_USER_AGENT'] : '';
} else {
// if the user agent doesnt validate, destroy the session and force relogin
if (!isset($_SERVER['HTTP_USER_AGENT']) || $_SESSION['user_agent'] !== $_SERVER['HTTP_USER_AGENT']) {
// destroy
session_destroy();
$_SESSION = array();
if (!headers_sent()) {
// set a flash and redirect to the login page
header('Status: 200');
header('Location: ' . urlencode('/login'));
exit;
} else {
// throw an error message
exit;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment