Session
Sessions are used to track and follow a user, as well as to store information for a single user across different and separate requests. By providing a comprehensive structure and supporting well-known session stores such as Memcached, Jalno makes accessing the user and their information easy.
This class uses three methods for storing user information, as described below:
With all of the above methods, you can use the following static methods to work with sessions.
| Method | Usage |
|---|---|
start(): void | Starting a session |
set(string $key, mixed $value): void | Defining a variable or storing data |
get(string $key): mixed | Getting a variable or retrieving data |
unset(string $key): void | Removing data |
destroy(): void | Destroying the session |
getID(): ?string | Getting the unique session ID |
Storage Methods
PHP's Default Logic
In PHP logic, when a session is started, a key named PHPSESSID is created in the user's browser cookies, storing a unique string value; a corresponding file with that same string as its name is created on the server. In the php.ini file, the storage location of session files can be seen in the session.save_path key.
Cache
If the cache is used to store sessions, storage is performed according to the cache method, which can take three forms: storing in a file, storing in a database, or using Memcache.
Specifying the Data Storage Method
By adding a setting named packages.base.cache with one of the values file (to store data in a file), memcache (to store data using memcache), or database (to store data in the database), you can specify the storage method.
If no storage method is specified, data is automatically stored in a file.
Using any of the three methods is identical, and the cache class automatically stores and manages the data with the specified method.
For more information, refer to the Cache page.
Database
Session information can also be stored in the database. With this method, the information is stored in the base_sessions table in the database.
Configuring the Session
First, the configuration must be done in Jalno's configuration file (config.php), which is located at packages/base/libraries/config.
In the packages.base.session setting, we configure the session-related values; it accepts an array with the indexes handler, autostart, and ip.
handler: Used to specify the data storage method; it accepts the values cache, mysql, and php.
Its default value is php.
autostart: Used to automatically create and start sessions; it accepts a boolean value.
If we do not set autostart to true, we must call the session::start() method at the beginning of every method in which we intend to work with sessions.
If you set autostart to true and also call session::start(), you will receive a Warning: session_set_cookie_params() error.
ip: If the value of the ip index is true, the SESSION_IP variable is automatically defined for the session and the user's IP is stored in it. The default value of this index is true.
If the value is true, then when the user's IP changes, the user's session is also changed and a new session is created for them.
'packages.base.session' => array(
'handler' => 'php', //cache, mysql, php
'ip' => true,
'autostart' => true
),
Starting a Session
To start sessions, the static start() method is used.
This method must be called before any other session methods are called.
To avoid extra code, you can set the packages.base.session["autostart"] setting to true in the packages/base/libraries/config/config.php file.
namespace packages\my_package\controllers;
use themes\my_theme\views;
use packages\base\{Response, Controller, Session, View};
class Panel extends Controller {
/*
'autostart' => false
*/
public function index(): Response {
Session::start();
if (!Session::get("login")) {
$this->response->Go(base\url("login"));
$this->response->setStatus(true);
return $this->response;
}
$view = View::byName(views\panel\Index::class);
$this->response->setView($view);
$this->response->setStatus(true);
return $this->response;
}
public function chat(): Response {
Session::start();
if (!Session::get("login")) {
$this->response->Go(base\url("login"));
$this->response->setStatus(true);
return $this->response;
}
$name = Session::get("name");
$view = view::byName(views\Chat::class);
$view->setName($name);
$this->response->setView($view);
$this->response->setStatus(true);
return $this->response;
}
}
namespace packages\my_package\controllers;
use themes\my_theme\views;
use packages\base\{Response, Controller, Session, View};
class Main extends Controller {
/*
'autostart' => true
*/
public function index(): Response {
if (!Session::get("login")) {
$this->response->Go(base\url("login"));
$this->response->setStatus(true);
return $this->response;
}
$view = View::byName(views\panel\Index::class);
$this->response->setView($view);
$this->response->setStatus(true);
return $this->response;
}
public function chat(): Response {
if (!Session::get("login")) {
$this->response->Go(base\url("login"));
$this->response->setStatus(true);
return $this->response;
}
$name = Session::get("name");
$view = view::byName(views\Chat::class);
$view->setName($name);
$this->response->setView($view);
$this->response->setStatus(true);
return $this->response;
}
}
Defining a Variable or Storing Data
To store data in sessions, the static set(string $key, mixed $value) method is used. The input arguments of this method are the data key name and the data value.
namespace packages\my_package\controllers;
use themes\my_theme\views;
use packages\my_package\User;
use packages\base\{Response, Controller, Session, View, Http, view\Error};
class Main extends Controller {
/*
'autostart' => true
*/
public function login(): Response {
$view = view::byName(views\Login::class);
$this->response->setView($view);
if (Http::is_post()) {
$inputs = $this->checkinputs(array(
"username" => array(
"type" => "email",
),
"password" => array()
));
$user = new User();
$user->where("email", $inputs["username"]);
$user->where("password", md5($inputs["password"]));
$user = $user->getOne();
if (!$user) {
throw new Error("invalid_username_or_password");
}
Session::set("login", true);
Session::set("userID", $user->id);
$this->response->Go(base\url("userpanel"));
} else {
$this->response->setStatus(true);
}
return $this->response;
}
}
Getting a Variable or Retrieving Data
To retrieve data that has been defined and stored in the session, the static get(string $key) method is used. The input argument of this method is the data key name.
If no data exists with the given key name, it returns false.
namespace packages\my_package\controllers;
use themes\my_theme\views;
use packages\base\{Response, Controller, Session, View};
class Main extends Controller {
/*
'autostart' => true
*/
public function panel(): Response {
if (!Session::get("login")) {
$this->response->Go(base\url("login"));
$this->response->setStatus(true);
return $this->response;
}
$view = view::byName(views\panel::class);
$this->response->setView($view);
$this->response->setStatus(true);
return $this->response;
}
}
Removing Data
To remove data stored under a session key, the unset(string $key) method is used. The input argument of this method is the name of the desired data key.
namespace packages\my_package\controllers;
use function packages\base\url;
use packages\base\{Response, Controller, Session};
class User extends Controller {
/*
'autostart' => true
*/
function logout(): Response {
Session::unset("login");
Session::unset("userID");
$this->response->Go(url("login"));
$this->response->setStatus(true);
return $this->response;
}
}
namespace packages\my_package\controllers;
use themes\my_theme\views;
use packages\my_package\ContactUs;
use packages\base\{Response, Controller, Session, View, InputValidationException};
class Main extends Controller {
/*
'autostart' => true
*/
public function contactUs(): Response {
$view = view::byName(views\ContactUs::class);
$this->response->setView($view);
if (Http::is_post()) {
$inputs = $this->checkinputs([
'name' => [
'type' => 'string'
],
'msg' => [
'type' => 'string'
],
'captcha' => [
'type' => 'string'
]
]);
if ($inputs["captcha"] != Session::get("captcha")) {
throw new InputValidationException("captcha");
}
$contactUs = new ContactUs();
$contactUs->msg = $inputs['msg'];
$contactUs->name = $inputs['name'];
$contactUs->save();
Session::unset("captcha");
$this->response->setStatus(true);
} else {
$this->response->setStatus(true);
}
return $this->response;
}
}
Destroying the Session
To destroy the session completely, the destroy() method is used. This method takes no input arguments.
namespace packages\my_package\controllers;
use function packages\base\url;
use packages\base\{Response, Controller, Session};
class Panel extends controller {
/*
'autostart' => true
*/
public function logOut(): Response {
Session::destroy();
$this->response->Go(url("login"));
$this->response->setStatus(true);
return $this->response;
}
}
Getting the Unique Session ID
Each session has a unique key, and this unique key can be used for various purposes, such as creating a shopping cart. This key is accessible through the getID method.
namespace packages\carjer;
use packages\base\{db\dbObject, Session, Date, Http};
class Cart extends dbObject {
/*
'autostart' => true
*/
public static function getCart(): Cart {
$id = Session::getID();
$cart = (new Cart)->byId($id);
if (!$cart) {
$cart = new Cart();
$cart->id = $id; // This is optional
$cart->save();
}
return $cart;
}
protected $dbTable = "carjer_carts";
protected $primaryKey = "id";
protected $dbFields = array(
"id" => array("type" => "text", "required" => true),
"ip" => array("type" => "text", "required" => true),
"created_at" => array("type" => "int", "required" => true),
);
protected $relations = array(
"products" => array("hasMany", Cart\Prodcut::class, "card_id"),
);
public function preLoad(array $data): array {
if (!isset($data["id"])) {
$data["id"] = Session::getID();
}
if (!isset($data["created_at"])) {
$data["created_at"] = Date::time();
}
if (!isset($data["ip"])) {
$data["ip"] = Http::$client["ip"];
}
return $data;
}
}