Created
March 25, 2012 14:34
-
-
Save cballou/2196124 to your computer and use it in GitHub Desktop.
Securing Your PHP Sessions - Helpers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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