Reading list Switch to dark mode

    Session Management in Opencart Version 3.x

    Updated 16 July 2021

    With the launch of Opencart Version 3, Opencart has discontinued the use of native session. Opencart has introduced the “maintaining of the session using database” in the version 2.2.0.0 and “maintaining using the file” in the version 2.3.0.0 but still, it continued to use the native PHP session ($_SESSION). In version 3, Opencart is using file by default to maintain the session.

    If you want to use the database for maintaining the session then you have to modify ‘default.php’ file residing at ‘system/config/’. You have to modify ‘session_engine’ index.

    // Session
    $_['session_engine']       = 'file'; // db or file can be placed

    You can take a look into the process of reading and writing of session in both db and file. For accessing the files, you can follow the path ‘system/library/session/’.

    File Session:

    Read:

    Searching for an experienced
    Opencart Company ?
    Find out More
    public function read($session_id) {
    	$file = $this->directory . '/sess_' . basename($session_id);
    
    	if (is_file($file)) {
    		$handle = fopen($file, 'r');
    
    		flock($handle, LOCK_SH);
    
    		$data = fread($handle, filesize($file));
    
    		flock($handle, LOCK_UN);
    
    		fclose($handle);
    
    		return unserialize($data);
    	} else {
    		return array();
    	}
    }

    Write:

    public function write($session_id, $data) {
    	$file = $this->directory . '/sess_' . basename($session_id);
    
    	$handle = fopen($file, 'w');
    
    	flock($handle, LOCK_EX);
    
    	fwrite($handle, serialize($data));
    
    	fflush($handle);
    
    	flock($handle, LOCK_UN);
    
    	fclose($handle);
    
    	return true;
    }

    DB Session:

    Read:

    public function read($session_id) {
    	$query = $this->db->query("SELECT `data` FROM `" . DB_PREFIX . "session` WHERE session_id = '" . $this->db->escape($session_id) . "' AND expire > " . (int)time());
    	
    	if ($query->num_rows) {
    		return $query->row['data'];
    	} else {
    		return false;
    	}
    }

    Write:

    public function write($session_id, $data) {
    	$this->db->query("REPLACE INTO SET `data` = '" . $this->db->escape($data) . "', expire = '" . $this->db->escape(date('Y-m-d H:i:s', time() + $this->expire)) . "' FROM `" . DB_PREFIX . "session` WHERE session_id = '" . $this->db->escape($session_id) . "' AND expire > " . (int)time());
    	
    	return true;
    }

    . . .

    Leave a Comment

    Your email address will not be published. Required fields are marked*


    Be the first to comment.

    Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home