It's better when it's simple

User Tools

Site Tools


Accessing Request Variables

DokuWiki does not prohibit access to the $_POST, $_GET, $_REQUEST and $_SERVER super globals. However we strongly recommend to access them not directly, but instead use our Input class. A global instance of that class is available everywhere as $INPUT.

The class gives you type safe access to the request variables, makes sure they are correctly initialized and allows you to set defaults.

To access a variable in $_REQUEST, just call the appropriate method on $INPUT. Eg. for accessing an Integer in $_REQUEST['foo'], just call $INPUT->int('foo').

If you want to access $_GET or $_POST explicitly, call the methods on the get and post members of $INPUT. Eg. $INPUT->get->int('foo') or $INPUT->post->int('foo').

Access to $_SERVER variables is always through the server member of $INPUT: Eg. $INPUT->server->str('REMOTE_USER').

All the access functions allow for a second parameter to set a default value. This value will be returned when the variable was not set or had the wrong type (eg. an expected integer was an array instead). All access functions have reasonable defaults matching the type of the function. Eg. int() returns 0, arr() returns an empty array as default.

A third parameter tells the function if an empty() parameter should be returned as default as well. This third parameter defaults to false.


Here are a couple of examples to give you an idea how the Input class works. For detailed info, please refer to inc/Input/Input.php.

global $INPUT;
$_REQUEST = ['foo' => '3'];
var_dump($INPUT->int('foo')); // expect an integer
// int(3)
var_dump($INPUT->str('foo')); // expect a string
// string(1) "3"
var_dump($INPUT->int('bar')); // standard default
// int(0)
var_dump($INPUT->int('bar',42)); // setting an explicit default
// int(42)
var_dump($INPUT->bool('foo')); // we cast when reasonable
// bool(true)
var_dump($INPUT->arr('foo')); // we don't cast here
// array(0) {
// }
var_dump($INPUT->has('foo')); // is set
// bool(true)
$_POST = ['foo' => '0', 'bar' => ''];
// now accessing $_POST and trying the third parameter 
var_dump($INPUT->post->int('foo', -1));
// int(0)
var_dump($INPUT->post->int('bar', -1));
// int(-1)
var_dump($INPUT->post->int('foo', -1, true));
// int(-1)
var_dump($INPUT->post->int('bar', -1, true));
// int(-1)
// string(8) "username"
devel/request_vars.txt · Last modified: 2023-09-20 23:27 by Klap-in

Except where otherwise noted, content on this wiki is licensed under the following license: CC Attribution-Share Alike 4.0 International
CC Attribution-Share Alike 4.0 International Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki