Skip to content

Instantly share code, notes, and snippets.

@jfortier-haptiq
Last active August 29, 2015 14:18
Show Gist options
  • Save jfortier-haptiq/abe4c45044db07412612 to your computer and use it in GitHub Desktop.
Save jfortier-haptiq/abe4c45044db07412612 to your computer and use it in GitHub Desktop.
GN21Cookie Managment
<?php
require_once 'gn21cookie.php';
//Encrypt and set the cookie
\GN21Session::encrypt( array(
'networkId'=>123,
'membershipLevel'=>'gold',
'clubId'=>2,
), true);
//Grabs content from cookie and decrypts it:
$fields = \GN21Session::decrypt();
//keep session alive - keeps renewing expiry
\GN21Session::keepalive();
//kill the session
\GN21Session::expire();
<?php
class GN21Session {
protected static $key = "f1c67bd9a01b3d10bcd717ec2baaf0c1";
protected static $cookie_name = "gn21_session";
protected static $cookie_path = "/";
protected static $cookie_domain = "golfcanada.ca";
protected static $cookie_expire = "+30 minutes";
/**
* Session properties into json encrypted string
*/
public static function encrypt ( array $payload, $set_cookie = false ) {
$payload = json_encode($payload);
$encrypted = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5(self::$key), $payload, MCRYPT_MODE_CBC, md5(md5(self::$key))));
if ($set_cookie) {
self::set($encrypted);
}
return $encrypted;
}
/**
* Extract encrypted session var
*/
public static function decrypt ( $encrypted_payload = null) {
if (is_null($encrypted_payload)) {
$encrypted_payload = self::get();
}
$json_string = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5(self::$key), base64_decode($encrypted_payload), MCRYPT_MODE_CBC, md5(md5(self::$key))), "\0");
$json = json_decode($json_string, true);
return $json;
}
/**
* Expire cookie
*/
public static function expire () {
setcookie(self::$cookie_name, "", strtotime("-1 minute"), self::$cookie_path, self::$cookie_domain );
}
/**
* Set the cookie data
*/
public static function set ( $encrypted, $cookie_expire = null ) {
if ( is_null($cookie_expire) ) {
$cookie_expire = self::$cookie_expire;
}
setcookie(self::$cookie_name, $encrypted, strtotime($cookie_expire), self::$cookie_path, self::$cookie_domain );
}
/**
* Get the data from the cookie
*/
public static function get () {
if ( array_key_exists(self::$cookie_name, $_COOKIE) ) {
return $_COOKIE[self::$cookie_name];
}
return null;
}
/**
* KeepAlive - Updates the expire time
*/
public static function keepalive () {
self::set( self::get() );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment