Created
September 13, 2012 03:19
-
-
Save daviddesberg/3711632 to your computer and use it in GitHub Desktop.
Client-side PHP Sessions
This file contains hidden or 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 | |
class ClientSideSessionHandler implements SessionHandlerInterface | |
{ | |
const SESSION_COOKIE_NAME = 'data'; | |
private $cryptor; | |
private $cookieJar; | |
private $encryptionKey; | |
private $signingKey; | |
public function __construct(Cryptor $cryptor, CookieJar $cookieJar, $encryptionKey, $signingKey) | |
{ | |
$this->cryptor = $cryptor; | |
$this->cookieJar = $cookieJar; | |
$this->encryptionKey = $encryptionKey; | |
$this->signingKey = $signingKey; | |
} | |
public function open($savePath, $sessionName) | |
{ | |
return true; | |
} | |
public function close() | |
{ | |
return true; | |
} | |
public function read($id) | |
{ | |
$data = $this->cookieJar->get( static::SESSION_COOKIE_NAME ); | |
if( !$this->cryptor->verify( $data, $this->signingKey ) ) { | |
throw new SessionAuthenticationException('Session cookie signature mismatch.'); | |
} | |
return $this->cryptor->decrypt( $data, $this->encryptionKey ); | |
} | |
public function write($id, $data) | |
{ | |
$data = $this->cryptor->sign( $this->cryptor->encrypt( $data, $this->encryptionKey ), $this->signingKey ); | |
$this->cookieJar->set( static::SESSION_COOKIE_NAME, $data ); | |
return true; | |
} | |
public function destroy($id) | |
{ | |
$this->cookieJar->remove( static::SESSION_COOKIE_NAME ); | |
return true; | |
} | |
public function gc($maxlifetime) | |
{ | |
return true; | |
} | |
} |
This file contains hidden or 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 | |
interface Cryptor | |
{ | |
function encrypt($blob, $key); | |
function decrypt($blob, $key); | |
function verify($blob, $key); | |
function sign($blob, $key); | |
} |
This file contains hidden or 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 | |
class SessionAuthenticationException extends RuntimeException {} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment