Skip to content

Instantly share code, notes, and snippets.

@ar00n
Last active May 1, 2018 15:26
Show Gist options
  • Save ar00n/ad381b412220414e91528a0d6defe39d to your computer and use it in GitHub Desktop.
Save ar00n/ad381b412220414e91528a0d6defe39d to your computer and use it in GitHub Desktop.
Generates a crypto secure cookie along with a hashed version for database storage. -ar0n#1462
<?php
$user = 'ar0n#1462';
// Valid till. Currently an hour.
$hour = time() + 3600 * 24 * 30;
// Generates crypto-secure string (hGlsUTlYvRcAQs8DA7vzER4R62x2gwyNQY8%3D), change random_bytes length for more security.
$pass = base64_encode(random_bytes(26));
// BCrypt hashes $id for database storage.
$dbinput = password_hash($pass, PASSWORD_DEFAULT);
// Gives cookie to user.
// '$hour' = time cookie is valid for.
// '/' = path the cookie is available on.
// 'yourdomain.com' = domain that the cookie works on.
// 'isset($_SERVER["HTTPS"])' = if HTTPS is enabled, only send cookie over secure connection.
// 'true' = httponly (accessible only through the HTTP protocol.) Prevents XSS.
setcookie('user', $user, $hour, '/', 'yourdomain.com', isset($_SERVER["HTTPS"]), true);
setcookie('pass', $pass, $hour, '/', 'yourdomain.com', isset($_SERVER["HTTPS"]), true);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment