Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a value from $_POST *not* be a string?

In PHP, can a value from the global $_POST array be something else than an array or a string?

The goal is to not have to check if everything is something else than an array or string in a script. If I know what type a variable has, I don't have to do some weird validation. If I expect a string, I don't have to cast everything to a string to make sure it is one.

like image 453
conradkleinespel Avatar asked Feb 19 '13 14:02

conradkleinespel


People also ask

What does $_ POST contain?

The $_POST variable is an array of variable names and values sent by the HTTP POST method. The $_POST variable is used to collect values from a form with method="post". Information sent from a form with the POST method is invisible to others and has no limits on the amount of information to send.

What does $_ POST mean in PHP?

PHP $_POST is a PHP super global variable which is used to collect form data after submitting an HTML form with method="post". $_POST is also widely used to pass variables. The example below shows a form with an input field and a submit button.

Is $_ POST an array?

The PHP built-in variable $_POST is also an array and it holds the data that we provide along with the post method.

Which variable will be used to pick the value using post method?

The $_REQUEST variable The PHP $_REQUEST variable can be used to get the result from form data sent with both the GET and POST methods.


3 Answers

$_POST["key"] = true;

var_dump($_POST["key"]); // bool(true)

The values set by the environment are strings though.

like image 198
Ocramius Avatar answered Sep 30 '22 19:09

Ocramius


As per the documentation http://php.net/manual/en/reserved.variables.post.php

An associative array of variables passed to the current script via the HTTP POST method. 

So all the data sent is in associative array, in key value pair. There are Numbers (int, float etc), Strings, Arrays (of numbers or strings) and Objects data types.

Using the rule of elimination we can remove the Object from the supported data type, and the remaining left are strings, numbers and array.

Now, if you see the form, the input fields are taking strings, there is no indication that the value entered in the input field is number or string. So to be on safe side all the values which are posted are in strings. The array of elements also have the string values.

When you get the value in $_POST it is simply an array and you can override it any time

$_POST['username'] = 1;
var_dump($_POST['username']); // int (1)

I hope this make some sense

like image 27
Aamir Mahmood Avatar answered Sep 30 '22 19:09

Aamir Mahmood


You can cast it to whatever you wish ^^

intval($_POST['INTEGER']);
or simply
 (int)$_POST['int']
like image 25
Iesus Sonesson Avatar answered Sep 30 '22 19:09

Iesus Sonesson