The pair opencartA free open-source CMS for online stores, written in PHP with a MySQL/MariaDB database. Everything that is not part of the core is added through extensions. More in the glossary → request response consists of two small core classes. Request takes a copy of the superglobal arrays $_GET, $_POST, $_COOKIE, $_FILES and $_SERVER once per request and then clears them. Response accumulates the response headers and body and outputs them to the browser at the very end. In a controllerCode that receives a request and prepares data. More in the glossary →, both are available as $this->request and $this->response. If you understand what they actually do with the data, you can avoid most of the strange module bugs: double escaping, "disappearing" headers, and JSON that won't parse. Examples are for OpenCart 4.1; in 4.0.x, model triggers and event handling differ.
Where do Request and Response live, and how do they reach the controller?
Both classes are located in system/library/: they are the files request.php and response.php. In OpenCart 3.0 these are global classes Request and Response. In OpenCart 4.1 they have the namespace Opencart\System\Library. For other places to look for core libraries, see the article about the OpenCart directory map.
system/ creates the objects at the start of every request, before any controller is called. They are also placed into the registry there. framework.php itself immediately adds the basic Content-Type header for HTML and passes the compression level from the store settings to Response. When the route has finished, the framework itself calls $response. The full chain is covered in the article on the request path from index.php to the controller. Why $this->request works in a controller without any new is explained in the article on Registry and magic access to objects.
An important rule follows from this. The Request object is one per request. All controllers, models, and modules invoked through $this see the same arrays. If one module changes $this, every subsequent one will see the change. Sometimes this is done deliberately, but more often it is a source of bugs.
flowchart TD
A["index.php"] --> B["framework.php: new Request()"]
B --> C["clean(): copies of $_GET, $_POST, $_COOKIE, $_FILES, $_SERVER"]
C --> D["Registry: request, response"]
D --> E["Controller reads $this->request"]
E --> F{"Redirect?"}
F -- "yes" --> G["header Location + exit()"]
F -- "no" --> H["addHeader() / setOutput()"]
H --> I["framework.php: response->output()"]
I --> J["gzip (if enabled) → header() → echo"]
How does Request clean GET and POST, and why does it matter?
The constructor does not check or validate anything. It simply passes each superglobal array through the clean() method:
system/ · OpenCart 3.0.5.1 · lines 24–50
public function __construct() {
$this->get = $this->clean($_GET);
$this->post = $this->clean($_POST);
$this->request = $this->clean($_REQUEST);
$this->cookie = $this->clean($_COOKIE);
$this->files = $this->clean($_FILES);
$this->server = $this->clean($_SERVER);
}
/**
*
* @param mixed $data
*
* @return array
*/
public function clean($data) {
if (is_array($data)) {
foreach ($data as $key => $value) {
unset($data[$key]);
$data[$this->clean($key)] = $this->clean($value);
}
} else {
$data = trim(htmlspecialchars($data ?? '', ENT_COMPAT, 'UTF-8'));
}
return $data;
}
Here is what to remember:
- Values arrive already HTML-escaped. A string
Tom & Jerryin$thiswill look like->request ->post Tom & Jerry. This is exactly the form in which OpenCart stores data in the database. That is why product descriptions on the storefrontWhat the customer sees: the home page, categories, product page, and cart. More in the glossary → pass throughhtml_entity_decode()when displayed. - Keys are escaped too. An array key from
<or&will change, and the usualisset()lookup by the "raw" name will not work. - Leading and trailing spaces are trimmed. This applies to passwords as well. That is how the core behaves, so do not try to "fix" this in your module. Otherwise login and registration will diverge.
ENT_COMPATdoes not touch single quotes. In other words,clean()is protection against XSS in an HTML context, not against SQL injection.
Another trap is double escaping. If a value from the request is passed through htmlspecialchars() again in the controller or template, the page will show &quot;. When you need the original text (an email, an API call, a file name), decode the value explicitly using html_entity_decode($value, ENT_QUOTES, 'UTF-8').
How does Request differ between OpenCart 3.0 and 4.1?
The cleaning logic is the same in both branches. But the interface changed in 4.1: the $request array is gone, and typed helpers get() and post() have appeared.
system/ · OpenCart 4.1.0.4 · lines 56–73
public function get(string $key, string $type = ''): mixed {
$value = $this->get[$key] ?? null;
switch ($type) {
case 'string':
return (string)$value;
case 'int':
return (int)$value;
case 'float':
return (float)$value;
case 'bool':
return (bool)$value;
case 'array':
return (array)$value;
default:
return $value;
}
}
| Aspect | OpenCart 3.0 | OpenCart 4.1 |
|---|---|---|
| Arrays | get, post, request, cookie, files, server | get, post, cookie, files, server (no request) |
| Read helpers | none, only isset() / ternary operator | get($key, $type), post($key, $type) |
| Namespace | global class | Opencart\System\Library |
| Property types | untyped | public array |
When porting a module from 3.0 to 4.1, the first thing that breaks is access to $this. In 4.1 this property does not exist. Decide explicitly where to take the parameter from: get or post. A helper called on a missing key returns null, and with a type it returns a "zero" value: 0, '', or an empty array. A missing product_id turns into 0 without any warning. So you should still check that the entity exists in the model.
An example of reading parameters in both versions:
// OpenCart 3.0
$product_id = isset($this->request->get['product_id']) ? (int)$this->request->get['product_id'] : 0;
// OpenCart 4.1
$product_id = $this->request->get('product_id', 'int');
$comment = $this->request->post('comment', 'string');
How do you correctly accept POST, files, and JSON bodies?
The request method is conventionally checked via $this. This is how forms work in OpenCart 3.0; in 4.1, forms are submitted via AJAX to methods such as save(). This array also went through clean(), but for REQUEST_METHOD that changes nothing.
Uploaded files
$this is cleaned in the same way as the other arrays. So the name of a file containing an ampersand or quotes will arrive escaped. Before saving, decode and sanitize the name yourself. tmp_name usually contains no special characters, but move the file only via move_uploaded_file() and check the extension and MIME type. The article on the directory structure (the section on storage) explains where to put the result so that it does not end up in a public folder.
JSON and raw request bodies
Request works only with the superglobal arrays. PHP does not parse the body of Content-Type: application/ in $_POST. So $this will be empty, and clean() does not touch such data at all. This is a typical case for payment systemA service that accepts cards: LiqPay, WayForPay, Monobank, and others. The commission depends on the contract. More in the glossary → callbacks, AJAX to fetch(), and integrations with warehouse software.
$raw = file_get_contents('php://input');
$data = json_decode($raw, true);
if (!is_array($data)) {
$this->response->addHeader($this->request->server['SERVER_PROTOCOL'] . ' 400 Bad Request');
$this->response->setOutput('');
return;
}
$order_id = isset($data['order_id']) ? (int)$data['order_id'] : 0;
Data from php://input is "raw." Escaping, validation, and signature verification are entirely up to you. You can see how this works in practice with Ukrainian acquiringA service from a bank or provider for accepting card payments. More in the glossary → in the example of the LiqPay module for OpenCart, where the callback arrives exactly this way. Also note setOutput('') in the example above: why the 400 status never reaches the client is explained in the section on common errors.
How does Response output HTML, JSON, and headers?
The controller prints nothing itself. It puts the finished string into setOutput(), and headers into an internal array via addHeader(). The actual sending happens once, in the output() method, which the framework calls:
system/ · OpenCart 4.1.0.4 · lines 140–152
public function output(): void {
if ($this->output) {
$output = $this->level ? $this->compress($this->output, $this->level) : $this->output;
if (!headers_sent()) {
foreach ($this->headers as $header) {
header($header, true);
}
}
echo $output;
}
}
This has several practical consequences:
header($header, true)replaces a header with the same name. YourContent-Type: application/, added later, will override the default HTML type from the framework.json - The status code is set with the same
addHeader(), using a protocol line. For example:$this.->request ->server['SERVER_PROTOCOL'] . ' 404 Not Found' - The
getHeaders()method exists only in 4.1. In OpenCart 3.0 the headers array is private, and it cannot be read from outside. - The output of child controllers (header, footer, column_left) does not go into Response.
$thisreturns a string that you pass into the template. For details, see the article on Loader and controller/view calls.->load ->controller()
A typical AJAX endpoint of a module looks like this (3.0 syntax; in 4.1 only the class declaration with the namespace differs):
public function save() {
$json = array();
if ($this->request->server['REQUEST_METHOD'] == 'POST') {
$email = isset($this->request->post['email']) ? $this->request->post['email'] : '';
if (!filter_var(html_entity_decode($email, ENT_QUOTES, 'UTF-8'), FILTER_VALIDATE_EMAIL)) {
$json['error'] = 'Невірний e-mail';
} else {
$json['success'] = 'Збережено';
}
}
$this->response->addHeader('Content-Type: application/json');
$this->response->setOutput(json_encode($json));
}
For an HTML page, the pattern is familiar: $this. In OpenCart 4.1, setOutput() accepts only string. Passing an array or null gives TypeError, whereas 3.0 would swallow anything.
How do redirects and gzip compression work?
redirect()
system/ · OpenCart 3.0.5.1 · lines 35–38
public function redirect($url, $status = 302) {
header('Location: ' . str_replace(array('&', "\n", "\r"), array('&', '', ''), $url), true, $status);
exit();
}
The method itself replaces & with &, so links containing $this can be passed as is. It also strips line breaks, which blocks header injection. The key point here is exit(). Nothing runs after the redirect: not the rest of the controller, not output(), and not after-events that would otherwise fire later. If you need to write something to the session or log before the redirect, do it before the call.
By default the status is 302. For permanent redirects (a changed product URL, moved categories), pass 301 as the second argument. If you need dozens or hundreds of such redirects, it is more convenient to manage them from the admin, for example with the Redirector 301 module, rather than hardcoding them in controllers.
Output compression
The compression level is set in System → Settings, on the Server tab, in the output data compression level field. The framework passes it to setCompression().

The compress() method silently returns uncompressed data in several cases:
- the browser did not send
gzipinAccept-Encoding; - the level is outside the range −1…9;
- the zlib extension is missing or
zlib.output_compressionis enabled; - the headers have already been sent.
Level 0 means "disabled." If nginx or Apache already compresses responses, set 0. Doing the work twice gives no gain and only loads PHP. A value of around 4–6 is a reasonable compromise when the server does not compress on its own. The exact choice depends on the hosting CPU.
What are the most common errors with Request and Response?
Most problems arise because the developer bypasses the deferred output mechanism or forgets about data cleaning:
echo,var_dump(), or a BOM in the module file. Any byte output beforeoutput()makesheaders_sent()true. Then headers set viaaddHeader()are silently ignored, gzip is not enabled, and JSON fails with a parsing error on the client. For debugging, write to$this.->log ->write() - Empty output "eats" the headers.
output()does nothing if$this->outputis false: an empty string or"0". So a 204 or 400 response without a body will not be sent viaaddHeader(). Add a minimal body, for examplejson_encode(['error' => 'bad request']), or set the code directly viahttp_response_code(). - Large files via
setOutput(). The entire content is held in memory as a string and then compressed as well. For price lists and archives, stream the file withheader()+readfile()and finish withexit(). - Modifying
$_GETdirectly. Request has already made a copy, so the core will not see changes made to the superglobal array. Change$this, but do it deliberately.->request ->get - Comparing with an escaped value. A check against
$thiswill not work, because there the value is->request ->post['q'] == 'a&b' a&b.
Look for logs of these errors in System → Maintenance → Error Logs. The path to the log file is set in the configs, as described in the article about config.php and system/config.

Summary
$this->requestis a cleaned copy of the superglobal arrays. Values there are HTML-escaped and trimmed, but not protected for SQL.- OpenCart 4.1 has no
$this, but it does have typed->request ->request get()andpost(). - Read JSON bodies and callbacks from
php://inputand validate them yourself. $this->responsedefers output. Do not print anything manually: set headers viaaddHeader(), and the body viasetOutput().- Empty output means the headers will not be sent.
redirect()ends the script viaexit(). - Enable gzip in OpenCart only when the server does not compress responses itself.
Next, it is worth understanding how these objects get into the registry and how a request reaches your controller. All the materials in this section are collected on the page OpenCart Architecture and Files.