[php] How to access route, post, get etc. parameters in Zend Framework 2

How can I get various parameters related to the page request in zf2? Like post/get parameters, the route being accessed, headers sent and files uploaded.

This question is related to php file-upload zend-route zend-framework2

The answer is


The easiest way to do that would be to use the Params plugin, introduced in beta5. It has utility methods to make it easy to access different types of parameters. As always, reading the tests can prove valuable to understand how something is supposed to be used.

Get a single value

To get the value of a named parameter in a controller, you will need to select the appropriate method for the type of parameter you are looking for and pass in the name.

Examples:

$this->params()->fromPost('paramname');   // From POST
$this->params()->fromQuery('paramname');  // From GET
$this->params()->fromRoute('paramname');  // From RouteMatch
$this->params()->fromHeader('paramname'); // From header
$this->params()->fromFiles('paramname');  // From file being uploaded

 

Default values

All of these methods also support default values that will be returned if no parameter with the given name is found.

Example:

$orderBy = $this->params()->fromQuery('orderby', 'name');

When visiting http://example.com/?orderby=birthdate, $orderBy will have the value birthdate.
When visiting http://example.com/, $orderBy will have the default value name.
 

Get all parameters

To get all parameters of one type, just don't pass in anything and the Params plugin will return an array of values with their names as keys.

Example:

$allGetValues = $this->params()->fromQuery(); // empty method call

When visiting http://example.com/?orderby=birthdate&filter=hasphone $allGetValues will be an array like

array(
    'orderby' => 'birthdate',
    'filter'  => 'hasphone',
);

 

Not using Params plugin

If you check the source code for the Params plugin, you will see that it's just a thin wrapper around other controllers to allow for more consistent parameter retrieval. If you for some reason want/need to access them directly, you can see in the source code how it's done.

Example:

$this->getRequest()->getRequest('name', 'default');
$this->getEvent()->getRouteMatch()->getParam('name', 'default');

NOTE: You could have used the superglobals $_GET, $_POST etc., but that is discouraged.


The easisest way to get a posted json string, for example, is to read the contents of 'php://input' and then decode it. For example i had a simple Zend route:

'save-json' => array(
'type' => 'Zend\Mvc\Router\Http\Segment',
            'options' => array(
                'route'    => '/save-json/',
                'defaults' => array(
                    'controller' => 'CDB\Controller\Index',
                    'action'     => 'save-json',
                ),
            ),
        ),

and i wanted to post data to it using Angular's $http.post. The post was fine but the retrive method in Zend

$this->params()->fromPost('paramname'); 

didn't get anything in this case. So my solution was, after trying all kinds of methods like $_POST and the other methods stated above, to read from 'php://':

$content = file_get_contents('php://input');
print_r(json_decode($content));

I got my json array in the end. Hope this helps.


require_once 'lib/Zend/Loader/StandardAutoloader.php';
$loader = new Zend\Loader\StandardAutoloader(array('autoregister_zf' => true));

$loader->registerNamespace('Http\PhpEnvironment', 'lib/Zend/Http'); 

// Register with spl_autoload:
$loader->register();

$a = new Zend\Http\PhpEnvironment\Request();
print_r($a->getQuery()->get()); exit;

If You have no access to plugin for instance outside of controller You can get params from servicelocator like this

//from POST
$foo = $this->serviceLocator->get('request')->getPost('foo'); 
//from GET
$foo = $this->serviceLocator->get('request')->getQuery()->foo;
//from route
$foo = $this->serviceLocator->get('application')->getMvcEvent()->getRouteMatch()->getParam('foo');

All the above methods will work fine if your content-type is "application/-www-form-urlencoded". But if your content-type is "application/json" then you will have to do the following:

$params = json_decode(file_get_contents('php://input'), true); print_r($params);

Reason : See #7 in https://www.toptal.com/php/10-most-common-mistakes-php-programmers-make


Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to file-upload

bootstrap 4 file input doesn't show the file name How to post a file from a form with Axios File Upload In Angular? How to set the max size of upload file The request was rejected because no multipart boundary was found in springboot Send multipart/form-data files with angular using $http File upload from <input type="file"> How to upload files in asp.net core? REST API - file (ie images) processing - best practices Angular - POST uploaded file

Examples related to zend-route

How to access route, post, get etc. parameters in Zend Framework 2

Examples related to zend-framework2

How to install PHP intl extension in Ubuntu 14.04 Could not open input file: composer.phar How to force composer to reinstall a library? How to do left join in Doctrine? You must enable the openssl extension to download files via https How to access route, post, get etc. parameters in Zend Framework 2