PHP-JWT LIBRARY
- This session library is based on JWT and not PHP
$_SESSION
. - Using this PHP-JWT library, in the
lib/JWT
folder.
RELATED CONFIG
- In
CORE-Config.php
:JWT_ALGO
Encryption algorithm, defaultHS256
.JWT_EXPIRE
Token expiry, default0
(none).JWT_ISSUER
Issuer name, set this to your company name or domain.JWT_SECRET
Private key, set this to your own. Generate a long and stinky random string.
LIB-Session.php - private $cookie
The “cookie template”. Change this to suit your project needs accordingly.
A QUICK TRACE & EXAMPLE
Not going to explain line-by-line. Here’s a quick example of using the session library to track user login.
FIRST VISIT – SIGN IN
- In
CORE-Go.php
–$_CORE->load("Session")
is already loaded by default, you don’t have to do “anything special”. - Think of
$_CORE->Session->data
as “sort of a replacement” for$_SESSION
. - When the user signs in, we put the user data into the session data –
$_CORE->Session->data["user"] = $_CORE->User->get(USERID)
. - Call
$_CORE->Session->save()
. This will create an encryptedcbsess
cookie containing$_CORE->Session->data
.
SUBSEQUENT VISITS
- User sends
cbsess
cookie back to the server. $_CORE->load("Session")
, this time round the constructor will “unpack” the cookie and put the data back into$_CORE->Session->data
.- To sign off, call
$_CORE->Session->destroy()
. This will clear thecbsess
cookie.
CONTROLLING COOKIE SAVE
lib/HOOK-SESS-Save.php
// (A) ONLY SAVE USER ID INTO JWT
if (isset($data["user"])) {
$data["user"] = ["user_id" => $data["user"]["user_id"]];
}
Sharp code ninjas would have noticed – Isn’t it stupid to save data such as the user password in the cookie? This is where “hooks” come in handy, HOOK-SESS-Save.php
will be called right before the cookie is created. Use this to remove whatever “stupid data” you don’t want to save in the cookie.
CONTROLLING COOKIE LOAD
lib/HOOK-SESS-Load.php
// (A) LOAD USER INFO INTO SESSION
if (isset($this->data["user"])) {
$user = $this->DB->fetch(
"SELECT * FROM `users` WHERE `user_id`=?", [$this->data["user"]["user_id"]]
);
if (is_array($user)) {
unset($user["user_password"]);
$this->data["user"] = $user;
} else {
$this->destroy();
throw new Exception("Invalid or expired session.");
}
}
Sharp code ninjas would have noticed – If we only save the user ID in the cookie, how are we going to get the rest of the user data? This is where another hook comes in handy. HOOK-SESS-Load.php
is called right after the cookie is unpacked. Use this to get more/check for more information.
LONG STORY SHORT
If you are still lost:
- Put all session data into
$_CORE->Session->data
. - Call
$_CORE->Session->save()
to “commit save”. - Call
$_CORE->Session->destroy()
to “end session”. - Use
HOOK-SESS-Save.php
to control what data to save into the cookie. - Use
HOOK-SESS-Load.php
to load more data when unpacking the cookie.