note 128788 added to function.session-set-save-handler
| From: | polygon dot co dot in at gmail dot com | Date: | Fri, 11 Aug 2023 09:44:01 +0000 |
| Subject: | note 128788 added to function.session-set-save-handler | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-220749@lists.php.net to get a copy of this message | ||
How to use Cookie for managing session data with encryption.
<?php
class MySessionHandler implements SessionHandlerInterface
{
function __construct()
{
// Store the key and IV somewhere safe
//$key = openssl_random_pseudo_bytes(32); // 256-bit key
//$iv = openssl_random_pseudo_bytes(16); // 128-bit IV
// Store the base64 key and IV somewhere safe
//$key_base64 = base64_encode($key);
//$iv_base64 = base64_encode($vi);
// Use the store base64 key and IV below
$key_base64 = 's8Livn/jULM6HDdPY76E3aXtfELdleTaqOC8HgTfW7M=';
$iv_base64 = 'nswqKP23TT+deVNuaV5nXQ==';
$this->key = base64_decode($key_base64);
$this->iv = base64_decode($iv_base64);
}
// Encryption
function encryptSess($plaintext)
{
return openssl_encrypt($plaintext, 'AES-256-CBC', $this->key, OPENSSL_RAW_DATA,
$this->iv);
}
// Decryption
function decryptSess($ciphertext)
{
return openssl_decrypt($ciphertext, 'AES-256-CBC', $this->key,
OPENSSL_RAW_DATA, $this->iv);
}
public function open($savePath, $sessionName): bool
{
ob_start(); // Turn on output buffering
return true;
}
public function close(): bool
{
return true;
}
#[\ReturnTypeWillChange]
public function read($id)
{
if (isset($_COOKIE[session_name()])) {
return (string)$this->decryptSess(base64_decode($_COOKIE[session_name()]));
} else {
return '';
}
}
public function write($id, $data): bool
{
$op = ob_get_clean();
$encryptedData = base64_encode($this->encryptSess($data));
setcookie(session_name(), $encryptedData, time() +
(ini_get("session.gc_maxlifetime")), '/');
echo $op;
return true;
}
public function destroy($id): bool
{
return true;
}
#[\ReturnTypeWillChange]
public function gc($maxlifetime)
{
return true;
}
}
$handler = new MySessionHandler();
session_set_save_handler($handler, true);
session_start();
var_dump($_SESSION);
$_SESSION['id'] = 10000;
echo '<br/>Hello World';
?>
----
Server IP: 45.112.84.4
Probable Submitter: 45.91.157.134 (proxied: 103.182.131.65)
----
Manual Page -- https://php.net/manual/en/function.session-set-save-handler.php
Edit -- https://main.php.net/note/edit/128788
Del: integrated -- https://main.php.net/note/delete/128788/integrated
Del: useless -- https://main.php.net/note/delete/128788/useless
Del: bad code -- https://main.php.net/note/delete/128788/bad+code
Del: spam -- https://main.php.net/note/delete/128788/spam
Del: non-english -- https://main.php.net/note/delete/128788/non-english
Del: in docs -- https://main.php.net/note/delete/128788/in+docs
Del: other reasons-- https://main.php.net/note/delete/128788
Reject -- https://main.php.net/note/reject/128788
Search -- https://main.php.net/manage/user-notes.php