A free and open-source book on ZF3 for beginners


4.5. Retrieving GET and POST Variables

To simply get a GET or POST variable from an HTTP request, you use the following code:

// Get a variable from GET
$getVar = $this->params()->fromQuery('var_name', 'default_val');

// Get a variable from POST
$postVar = $this->params()->fromPost('var_name', 'default_val');

In the example above, we used the Params controller plugin, which provides you with convenient methods of accessing GET and POST variables, uploaded files, etc.

In line 2 we use the fromQuery() method for retrieving a variable having name "var_name" from GET. If such a variable does not present, the default value "default_val" is returned. The default value is very convenient, because you don't have to use the isset() PHP function to test if the variable exists.

In line 5 we use the fromPost() method to retrieve the variable from POST. The meaning of this method's parameters is the same as for the fromQuery() method.

In ZF3, you must not access request parameters through traditional PHP $_GET and $_POST global arrays. Instead, you use ZF3-provided API for retrieving the request data.


Top