No results found

Try a different search query

Popular searches:

Add to Cart

Cart

You have no purchases yet

Browse Marketplace
Original Subtotal:
Product discounts:
Quantity Discount:
Total:
View Cart
Architecture and files

OpenCart session and cache: how session and cache drivers work in 3.0 and 4.1

How OpenCart stores sessions and cache, which drivers are available in 3.0 and 4.1, where to switch them, how to write your own adapter, and where module developers most often go wrong.

13 min read OC 3.0 OC 4.1

Sessions in OpenCart are an object Session with an array $this->session->data. It does not use the PHP $_SESSION. A swappable driver (adaptor) reads and writes the data: a database, files, or your own class. The cache works the same way: the Cache class only delegates calls to the get/set/delete adaptor, and the adaptor is chosen in the config. Below is how this works in OpenCart 3.0 and 4.1, where to switch drivers, and what module developers should know so they don't break the cart or login. Examples are for OpenCart 4.1; in 4.0.x, model triggers and event handling differ.

How Session and Cache are built: a wrapper plus an adaptor

Both classes live in system/library/, and their drivers are in the subdirectories system/library/session/ and system/library/cache/. The location in the project tree is shown in the article about the directory map: file structure of OpenCart 3.0 and 4.1. The wrapper itself is thin. The constructor receives the adaptor name as a string, builds a class name from it, and creates an instance. Here is what this looks like for the session in 3.0:

system/library/session.php · OpenCart 3.0.5.1 · lines 24–39

public function __construct($adaptor, $registry = '') {
	$class = 'Session\\' . $adaptor;
	
	if (class_exists($class)) {
		if ($registry) {
			$this->adaptor = new $class($registry);
		} else {
			$this->adaptor = new $class();
		}	
		
		register_shutdown_function(array($this, 'close'));
	} else {
		trigger_error('Error: Could not load cache adaptor ' . $adaptor . ' session!');
		exit();
	}	
}

Three things are visible here. First: the adaptor is looked up in the Session\ namespace. In OpenCart 4.1 it is Opencart\System\Library\Session\, and the autoloader pulls the files from system/library/session/. Second: the session write is registered via register_shutdown_function, which means it happens at the very end of script execution, not at the moment of assignment. Third: if the adaptor is missing, 3.0 does exit() with a message that wrongly says "cache adaptor". Don't be surprised when you see it in the logs because of a typo in the session driver name.

The Cache class is built the same way: 'Cache\\' . $adaptor in 3.0 and 'Opencart\System\Library\Cache\\' . $adaptor in 4.1, and the constructor receives the lifetime $expire (default 3600 seconds). Both objects are created during framework initialization and placed in the registry. That is why they are available in controllers and models as $this->session and $this->cache. The mechanics are described in the article how Registry passes objects to the controller.

Which drivers come out of the box, and where do you switch them?

Driver names are set by the configuration keys session_engine and cache_engine. The default values are in system/config/default.php, and system/config/catalog.php and system/config/admin.php can override them. How these files are merged with each other and with settings in the database is explained in config.php, system/config and settings in the DB.

WhatOpenCart 3.0OpenCart 4.1
Default session driverdb (table session with the DB prefix)db
Other session drivers in the corefilefile, redis
Default cache driverfile (cache directory in storage)file
Other cache driversin 3.0.4.1: apc, mem, memcached, redis; apcu added in 3.0.5.1apcu, mem, memcached, redis (no apc)
Cleaning up session garbagedepends on the adaptora separate gc() method, called on shutdown
Lifetime for an individual cache keynone, only the global $expirethird argument of set($key, $value, $expire)
Full cache clear from codeno method in the wrapper$this->cache->clear()

The driver cannot be switched from the admin panel, only through config files. The most common approach is to create a separate config and include it, or to change default.php and record the change in your upgrade notes, because the file will be overwritten when the core is updated. Network cache drivers (redis, memcached, mem) take the server address from constants such as CACHE_HOSTNAME, CACHE_PORT and CACHE_PREFIX. They are declared in config.php of each application, that is, separately for catalog and for admin. Check the adaptor file to see which constants your version expects: without them, the driver will fail with a fatal error on the very first request.

How a session lives through a single request

The session ID is passed in a cookie, which in the default configuration is named OCSESSID (key session_name). In 3.0 the session is started by system/framework.php if session_autostart is enabled. In 4.1 this is done by the application's session startup controllerCode that receives a request and prepares data. More in the glossary →. The overall picture of request processing is described in the article the path from index.php to the controller. The start() method either generates a new ID or validates the received one:

system/library/session.php · OpenCart 4.1.0.4 · lines 65–79

public function start(string $session_id = ''): string {
	if (!$session_id) {
		$session_id = substr(bin2hex(openssl_random_pseudo_bytes(26)), 0, 26);
	}

	if (preg_match('/^[a-zA-Z0-9,\-]{22,52}$/', $session_id)) {
		$this->session_id = $session_id;
	} else {
		throw new \Exception('Error: Invalid session ID!');
	}

	$this->data = $this->adaptor->read($session_id);

	return $session_id;
}

An invalid ID (someone put junk in the cookie) stops the script with exit('Error: Invalid session ID!') in 3.0, and throws an exception in 4.1. After that, the entire session content is read in one call to read() into the $this->data array. The code works with this array in memory, and at the end of execution close() writes it back in full.

sequenceDiagram
    participant B as Browser
    participant S as Session
    participant A as Adaptor (db/file)
    participant C as Controller
    B->>S: cookie OCSESSID
    S->>A: read(session_id)
    A-->>S: data array
    C->>S: changes session->data
    Note over S: end of script (shutdown)
    S->>A: write(session_id, data)
    S->>A: gc() — 4.1 only

This leads to a non-obvious behavior: parallel requests overwrite each other's session. Suppose two AJAX requests fly out of a page at once: one adds a product to the cart, the other changes the currency. Both read the old version of data, each changed its own key, and whichever finishes last writes its array in full. The change from the first request disappears. There is no row-level locking in the database. So in your modules, don't run several "writing" AJAX requests against the session at the same time; if there is no way around it, queue them on the frontend.

How to work correctly with $this->session in a module

Reading and writing come down to working with an array. A few rules will save you from most bugs:

  • Prefix your keys. The core already uses customer_id, cart, currency, language, shipping_method, payment_method and others. A name like mymodule_step will not collide with the core, but step might.
  • Store only scalars and arrays. The driver serializes the data. Objects, resources and closures either won't be saved or will be restored as something other than what you put in.
  • Don't keep large data in the session. The whole array is read and written on every request, so a search result of 5,000 products in the session will slow down every page for that visitor.
  • Clean up after yourself with unset() when a scenario finishes, for example after a successful order placement.
  • Don't call destroy() for "logout". The core logs out precisely, removing the specific keys. Destroying the whole session also wipes the cart, language and currency.
// catalog/controller/extension/mymodule/wizard.php (3.0) — приклад
if (!isset($this->session->data['mymodule_wizard'])) {
	$this->session->data['mymodule_wizard'] = ['step' => 1, 'answers' => []];
}

$this->session->data['mymodule_wizard']['answers'][] = (int)$this->request->post['answer'];

// після фіналу сценарію
unset($this->session->data['mymodule_wizard']);

A special case is the admin. OpenCart 3.0: access to admin pages, besides the session, is protected by the user_token parameter in the URL. OpenCart 4.1: likewise user_token. If your module generates links in the admin without the token, the user will be kicked to the login page even though the session is alive. More about protecting the panel is in the article about OpenCart admin security. How to read cookies and headers through the request object instead of superglobal arrays is described in Request and Response in OpenCart.

How to use the cache and avoid serving stale data

The cache in OpenCart is a simple "key → value" store with a lifetime. The core caches reference data that rarely changes (currencies, languages, zones, and so on). When editing in the admin, models delete the corresponding keys. Your module should behave the same way: cache expensive things, and reset the cache when data changes.

system/library/cache.php · OpenCart 4.1.0.4 · lines 61–87

public function set(string $key, $value, int $expire = 0): void {
	$this->adaptor->set($key, $value, $expire);
}

/**
 * Delete
 *
 * Deletes a cache by key name.
 *
 * @param string $key The cache key
 *
 * @return void
 */
public function delete(string $key): void {
	$this->adaptor->delete($key);
}

/**
 * Clear
 *
 * Clear all cache
 *
 * @return void
 */
public function clear(): void {
	$this->adaptor->clear();
}

Key scheme

The key must include everything the result depends on: language, store, customer groupA segment of buyers (retail, wholesale) with different prices and terms. More in the glossary →, currency if the value contains prices. A typical format uses dots: mymodule.bestsellers.{store_id}.{language_id}.{customer_group_id}. The file adaptor deletes keys by a mask cache.{key}.*, so delete('mymodule') removes all derived mymodule.* keys. Network adaptors usually cannot do this, and there delete() deletes only the exact key. If your module must work with any driver, keep a list of your own keys, or embed a "version" in the prefix that you increment whenever the data changes.

// модель вітрини, приклад
$key = 'mymodule.top.' . (int)$this->config->get('config_store_id') . '.' . (int)$this->config->get('config_language_id');

$data = $this->cache->get($key);

if (!$data) {
	$query = $this->db->query("SELECT product_id FROM `" . DB_PREFIX . "product` WHERE status = '1' ORDER BY viewed DESC LIMIT 10");
	$data = $query->rows;

	$this->cache->set($key, $data);
}

Note the if (!$data) check: an empty array will also count as a miss, and the query will run every time. For "legitimately empty" results, cache a marker, for example ['empty' => true]. One more difference between versions. OpenCart 3.0: set() takes only two arguments, so all keys have the same lifetime (cache_expire). OpenCart 4.1: you can pass your own $expire for an individual key. Code that must work on both branches should not pass a third argument.

The built-in cache covers data, not ready-made HTML. To cache full pages and reduce TTFB, a separate layer is needed. An overview of this approach is in the article about caching and PageSpeed with Jet Cache, and the module itself is Jet Cache.

How to clear the cache and find a driver error in the admin?

Cache data is cleared from code via delete() (in 4.1 also via clear()). Manually, the file cache can be cleared by deleting the cache.* files in the cache directory inside storage. Don't touch the index.html file in that directory itself. In the admin, the Dashboard has a developer settings button with a gear icon. It is used to clear the theme and SASS cache. This button does not clear the model data cache.

Dashboard: the gear button in the upper right corner opens developer settings for clearing the theme cache
Dashboard: the gear button in the upper right corner opens developer settings for clearing the theme cache · OpenCart 4.1.0.4

If the site shows a blank page after changing session_engine or cache_engine, first open System → Maintenance → Error Logs. Look for the lines "Could not load cache adaptor" or "Could not load session adaptor". They mean the class was not found: a typo in the name, the file is in the wrong directory, or the namespace is incorrect. If the admin itself won't open, check the same log directly in the file in the logs directory storage.

Error log: shows the message about a missing cache or session adaptor
Error log: shows the message about a missing cache or session adaptor · OpenCart 4.1.0.4

How to write your own session adaptor

When several web servers sit behind a load balancer, it is convenient to keep sessions in Redis. In OpenCart 4.1 the redis driver is already in the core (system/library/session/redis.php), so it is enough to set session_engine = 'redis' and configure the connection. A custom Redis adaptor is needed only in 3.0, where only db and file come out of the box. For another storage, write your own driver. It must implement the same methods the wrapper calls: read($session_id), write($session_id, $data), destroy($session_id), and in 4.1 also gc(), because the constructor registers it:

system/library/session.php · OpenCart 4.1.0.4 · lines 35–45

public function __construct(string $adaptor, \Opencart\System\Engine\Registry $registry) {
	$class = 'Opencart\System\Library\Session\\' . $adaptor;

	if (class_exists($class)) {
		$this->adaptor = new $class($registry);
		register_shutdown_function([&$this, 'close']);
		register_shutdown_function([&$this, 'gc']);
	} else {
		throw new \Exception('Error: Could not load session adaptor ' . $adaptor . ' session!');
	}
}
  1. Create a file in system/library/session/ with a lowercase name, for example redis.php for 3.0. In 4.1 choose a different name, say mystore.php, because the redis.php file would overwrite the built-in driver.
  2. Declare the class in the correct namespace: namespace Session; with the class Redis for 3.0, namespace Opencart\System\Library\Session; with a class matching the file name for 4.1. To avoid confusion with the PHP \Redis extension, refer to it inside the code by its full name.
  3. The constructor receives $registry. Take config from there if the connection parameters are in the configuration.
  4. read() must always return an array, even when there is no record. write() sets a TTL so that old sessions disappear on their own, and then gc() can be left empty.
  5. Set the name in session_engine for catalog and admin, then check login, the cart and order placement.

The cache adaptor is written on the same principle: a class in system/library/cache/ with the methods get, set, delete, in 4.1 also clear, and the constructor receives $expire. How the autoloader finds such classes and how this differs from loading models is explained in the article about Loader in OpenCart.

Summary

  • Session and Cache are thin wrappers. The behavior is defined by the adaptors in system/library/session/ and system/library/cache/, and the choice is set by the keys session_engine and cache_engine.
  • The session is read as one block at startup and written in full on shutdown, so parallel AJAX requests can overwrite each other's changes.
  • OpenCart 4.1 added gc() for sessions, clear(), and a custom TTL in set() for the cache. Version 3.0An older branch with a large number of ready-made modules; many stores still run on it. More in the glossary → has none of these.
  • Build cache keys with the store, language and customer group in mind, and reset them when data changes. Prefix-based deletion is guaranteed only in the file driver.
  • The cache driver in admin and catalog must match. Look for adaptor loading errors in the error logThe error.log file, visible in "System → Maintenance → Error Logs." The first place to look when something breaks. More in the glossary →.

Next, it is worth understanding how these objects get into the registry during application startup, and going through the remaining topics of the section "Architecture and files".

FAQ

Can you use plain $_SESSION in OpenCart?
Technically you can start a PHP session, but the core does not read it, and the data will not be linked to the OpenCart cart or login. Work through $this->session->data, and your module will then work correctly with any driver.
Why does the customer get logged out after moving to another domain or subdomain?
The session cookie is tied to the domain, so the browser simply does not send the old identifier to the new host. Check the addresses in config.php and the cookie settings, and also HTTPS if the cookie has the secure flag.
How long are sessions stored in the database?
It depends on the version and settings: in 4.1 the lifetime is set by the session configuration, while in 3.0 it follows PHP and adapter parameters. If the session table is growing too large, check whether cleanup of old records is running.
Do you need to clear the cache after installing a module?
Usually you don't need to clear the data cache if the module invalidates its own keys. After installing modifications or changing templates, refresh the modifications and clear the theme cache, otherwise the changes may not appear.
Will Redis caching noticeably speed up a small store?
On a single server with an SSD, the difference from file caching is often small, because OpenCart mostly caches small reference data. Redis makes sense with several web servers or heavy load, while the biggest page speed gains come from full-page caching.
Was this article helpful?
Thanks for your feedback!

Related articles

Didn't find the answer?

Ask the community: OpenCart developers answer on the forum.

Ask on the forum
We use cookies

We use cookies and similar technologies to improve your experience, analyse traffic, and show personalised ads. Read our Cookie Policy for details.