Skip to content

Instantly share code, notes, and snippets.

@rigwild
Last active August 15, 2018 16:28
Show Gist options
  • Save rigwild/f3b2f9ed600308fa1714988e20aca6ad to your computer and use it in GitHub Desktop.
Save rigwild/f3b2f9ed600308fa1714988e20aca6ad to your computer and use it in GitHub Desktop.
A PHP secure login cookie system
<?php
$connexion = new PDO('mysql:host=' . $host . ';port=' . $port . ';dbname=' . $dbname, $user, $pass);
$connexion->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$connexion->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Cookie session validity duration (Default = 2 weeks)
$cookieSessionTimeout = 3600 * 24 * 14;
function createLoginCookie()
{
global $connexion;
global $cookieSessionTimeout;
$sess_id = bin2hex(random_bytes(50));
$unsecureRandomStr = bin2hex(random_bytes(50));
$sess_hash = password_hash($unsecureRandomStr, PASSWORD_DEFAULT);
$sess_timeout = time() + $cookieSessionTimeout;
$query = 'INSERT INTO logsession values (:sess_id, :sess_hash, :sess_timeout)';
$stmt = $connexion->prepare($query);
if ($stmt->execute(array(
'sess_id' => $sess_id,
'sess_hash' => $sess_hash,
'sess_timeout' => $sess_timeout,
)))
{
/*Session added in db*/
setcookie("sess_id", $sess_id, $sess_timeout, null, null, true, true);
setcookie("sess_content", $unsecureRandomStr, $sess_timeout, null, null, true, true);
return true;
}
else return false;
}
function checkLoginCookie()
{
global $connexion;
if (empty($_COOKIE['sess_id']) || empty($_COOKIE['sess_content']))
return false;
$sess_id = $_COOKIE['sess_id'];
$sess_content = $_COOKIE['sess_content'];
$query = 'SELECT * FROM logsession WHERE sess_id = :sess_id';
$stmt = $connexion->prepare($query);
if ($stmt->execute(['sess_id' => $sess_id]) && $stmt->rowCount() == 1)
{
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if (password_verify($sess_content, $row['sess_hash']) && time() < $row['sess_timeout'])
return true;
}
setcookie("sess_id", '', time() - 1000, null, null, true, true);
setcookie("sess_content", '', time() - 1000, null, null, true, true);
return false;
}
?>
CREATE TABLE `logsession` (
`sess_id` varchar(100) NOT NULL,
`sess_hash` varchar(100) NOT NULL,
`sess_timeout` timestamp NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment