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 Request Response: GET/POST, Headers, Output

How OpenCart 3.0 and 4.1 read GET, POST, cookies and files via Request, and return HTML, JSON, headers and redirects via Response. We explain data cleaning, gzip and common errors.

11 min read OC 3.0 OC 4.1

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/framework.php 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->output(). 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->load->controller() see the same arrays. If one module changes $this->request->get['route'], 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/library/request.php · 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 & Jerry in $this->request->post will look like 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 through html_entity_decode() when displayed.
  • Keys are escaped too. An array key from < or & will change, and the usual isset() 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_COMPAT does 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 &amp;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/library/request.php · 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;
		}
	}
AspectOpenCart 3.0OpenCart 4.1
Arraysget, post, request, cookie, files, serverget, post, cookie, files, server (no request)
Read helpersnone, only isset() / ternary operatorget($key, $type), post($key, $type)
Namespaceglobal classOpencart\System\Library
Property typesuntypedpublic array

When porting a module from 3.0 to 4.1, the first thing that breaks is access to $this->request->request[...]. 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->request->server['REQUEST_METHOD']. 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->request->files 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/json in $_POST. So $this->request->post 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/library/response.php · 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. Your Content-Type: application/json, added later, will override the default HTML type from the framework.
  • 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. $this->load->controller() returns a string that you pass into the template. For details, see the article on Loader and controller/view calls.

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->response->setOutput($this->load->view('...', $data)). 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/library/response.php · OpenCart 3.0.5.1 · lines 35–38

	public function redirect($url, $status = 302) {
		header('Location: ' . str_replace(array('&amp;', "\n", "\r"), array('&', '', ''), $url), true, $status);
		exit();
	}

The method itself replaces &amp; with &, so links containing $this->url->link() 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().

Server tab: output data compression level field
Server tab: output data compression level field · OpenCart 4.1.0.4

The compress() method silently returns uncompressed data in several cases:

  • the browser did not send gzip in Accept-Encoding;
  • the level is outside the range −1…9;
  • the zlib extension is missing or zlib.output_compression is 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:

  1. echo, var_dump(), or a BOM in the module file. Any byte output before output() makes headers_sent() true. Then headers set via addHeader() are silently ignored, gzip is not enabled, and JSON fails with a parsing error on the client. For debugging, write to $this->log->write().
  2. Empty output "eats" the headers. output() does nothing if $this->output is false: an empty string or "0". So a 204 or 400 response without a body will not be sent via addHeader(). Add a minimal body, for example json_encode(['error' => 'bad request']), or set the code directly via http_response_code().
  3. 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 with header() + readfile() and finish with exit().
  4. Modifying $_GET directly. Request has already made a copy, so the core will not see changes made to the superglobal array. Change $this->request->get, but do it deliberately.
  5. Comparing with an escaped value. A check against $this->request->post['q'] == 'a&b' will not work, because there the value is a&amp;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.

Error log: showing
Error log: showing "headers already sent" and a TypeError from setOutput · OpenCart 4.1.0.4

Summary

  • $this->request is 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->request->request, but it does have typed get() and post().
  • Read JSON bodies and callbacks from php://input and validate them yourself.
  • $this->response defers output. Do not print anything manually: set headers via addHeader(), and the body via setOutput().
  • Empty output means the headers will not be sent. redirect() ends the script via exit().
  • 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.

FAQ

Can I get the 'raw', unescaped POST value in OpenCart?
Not through Request, which only stores a cleaned copy. You can decode the value with html_entity_decode() or, as a last resort, access $_POST directly, knowing that you will then have to do all the validation yourself.
How do I output XML, for example a feed for a marketplace?
Add the header Content-Type: application/xml; charset=utf-8 via addHeader() and pass the finished XML string to setOutput(). For very large feeds, it's better to generate the file in advance with a cron job and serve it statically.
Why doesn't the cookie I set with setcookie() appear in $this->request->cookie in the same request?
Request reads $_COOKIE once at startup, so a new cookie will only appear there with the browser's next request. Within the current request, store the value in a variable or in the session.
Does Request affect SEO URLs?
Yes, the SEO URL handler parses the address and writes the route and parameters into $this->request->get, so the controller sees them just like regular GET parameters.
Is it safe to disable gzip in OpenCart if the server handles compression?
Yes, level 0 in the settings only disables compression at the PHP level. Check in DevTools that the response still arrives with Content-Encoding: gzip from the web server.
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.