How to use Database ( MongoDb ) as session Handler PHP - 2016 ~ Coding Savvy
Coding Savvy FB Twitter Google
» »

How to use Database ( MongoDb ) as session Handler PHP - 2016

By default PHP has an inbuilt session handler that stores session variable by saving session variables into a file. The native sessions just depend on writing a small cookie and file on the server. Database based session allows you to add security functionality to the session layer, Any performance lose or gain by putting your sessions in a database won't be noticeable for the vast majority of applications, however it's more secure if you put your sessions in the database, that being the most developers primary reason for doing so. Database-based sessions are also perfect in server farm environments because a user could visit each server in the course of their visit; file-based sessions would only be valid on that one server. But we can override PHP's built-in session handlers by using session_set_save_handler . When your app gets big and you start thinking of scaling Database based session makes things easier. MongoDB (from humongous) is a free and open-source cross-platform document-oriented database. You can read more about MongoDB at http://www.mongodb.org. Using MongoDb is a way of separating the session management database from the primary sever Database, It is well known that most PHP websites use MySQL as their primary database. I prefer not to let the session handler implementation affect the primary database performance. MongoDb can also store some special data format and an Object as a whole without any data loss.
How to use Database ( MongoDb ) as session Handler PHP
Download Script
 To properly overide the default PHP session handler we need to use session_set_save_handler . It is necessary for the costume session handler method implement SessionHandlerInterface Interface so as to incorporate the required session handling methods like open() , close(),read(),write(),destroy() and finally the garbage collection method gc() these methods are useful to complete our session handler class.
session_set_save_handler($this, true);
 session_set_save_handler(array($this, 'open'),array($this, 'close'),array($this, 'read'),
array($this, 'write'),array($this, 'destroy'),array($this, 'gc'));
 register_shutdown_function('session_write_close');
We are going to implement the open() method like so:
public function open($savePath=null, $sessionName=null)
 {
 $this->_link->connect();
 return $this->_link->_isConnected;
 }
The open() method is a simple method, It ensures that our database is set to receive data, it enable connection to the database (MongoDb). Now let write the close() method:
public function close() {
 $this->gc(get_cfg_var("session.gc_maxlifetime"));
 $this->_link->disconnect();
 return !$this->_link->_isConnected;
 }
Let see the write and read method :

public function read($id) {
 $result = $this->_link->from($this->_schema)->where("active = ?",true) ->where("id = ?",$id)->where("expires > ?",New \MongoDB\BSON\UTCDateTime(time()))->first();
 if($result){ return $result->data;}
 else {return null;}
 }

 public function write($id, $data) {
 $diff = 60 * $this->_increment;
 $mongotime = New \MongoDB\BSON\UTCDateTime(time()+$diff);
 $result = $this->_link->from($this->_schema)->where("id = ?", $id)->where("active = ?", true) ->save(array("id" => $id, "active"=>true, "expires" => $mongotime, "data" => $data,"ip" =>$this->_ip));
 return $result;
 }

 public function destroy($id) {
 $result = $this->_link->from($this->_schema) ->where("id = ?",$id)->delete();
 return $result;
 }
Finally to make use of our session handler class in any PHP file:
include "include/session.php";
 /*inject your session database as parameter
*if database dosent exists Mongodb will create it for you.
*/
 /*Initiate session */
$session = new Session("myAppSession");
 /*
 *Add item to session
*/
 $_SESSION["foo"]="Bar";
 /*
*get itemfrom session */

/*Regular string from session*/
 var_dump($_SESSION["foo"]);
 /*
*adding object to session
*/
 class user { public $name="Peters"; public $hobbies=array("coding"); }
 $olduser = new user();

/*Username before saving to session*/
 echo $olduser->name;
 /*
*Save user object inside database
*/
$_SESSION["user"] = serialize($olduser);
 /*
*Get user object from session
*/

$newuser = unserialize($_SESSION["user"]);

/*Username after retreiving from session*/

echo $newuser->name;
Was this article helpful?
Thanks! Your feedback helps us improve tutorials.

You May Also Like...

No comments:

Post a Comment