How to access all values posted to PHP server - php

I first thought it was in the $_POST super global, but it isn't if values are included in the URL.
$_REQUEST did so and surprised me by not including cookies (reference http://php.net/manual/en/reserved.variables.request.php), and I later found that I am evidently using the default distribution php.ini file which does not contain the 'C' for cookies (reference http://php.net/manual/en/ini.core.php#ini.request-order). I don't wish to use $_REQUEST, however, as it doesn't differentiate between a get request, and changing servers and php.ini files could cause a security concern.
What is the proper way to access all post values?
EDIT. I added the $real_post part. Is this the proper way to do so?
<?php
setcookie('cookie', 'COOKIE', time() + (86400 * 30), "/");
echo('$_GET<pre>'.print_r($_GET,1).'</pre>');
echo('$_POST<pre>'.print_r($_POST,1).'</pre>');
echo('$_COOKIE<pre>'.print_r($_COOKIE,1).'</pre>');
echo('$_REQUEST<pre>'.print_r($_REQUEST,1).'</pre>');
$real_post=($_SERVER['REQUEST_METHOD'] == 'POST')?array_merge($_GET,$_POST):array();
echo('$real_post<pre>'.print_r($real_post,1).'</pre>');
?>
<form action='postorget.php?get=GET' method='post'>
<input type='text' name='post' value='POST'>
<input type='submit'>
</form>
$_GET
Array (
[get] => GET )
$_POST
Array (
[post] => POST )
$_COOKIE
Array (
[cookie] => COOKIE )
$_REQUEST
Array (
[get] => GET
[post] => POST )

You could do something like:
$uVariables = array("GET" => $_GET, "POST" => $_POST, "COOKIES" => $_COOKIES, "SESSION" => $_SESSION);
and then use json_encode() for database storage. Should you later decide to build a log viewer you can just use json_decode() and get everything back in original state.

Sorry, your question is a little unclear. Parameters appended to the URL (as you mention in the beginning) are GET parameters, so they are contained in the $_GET superglobal. They simply are not POST variables. So what is your question here? You could combine $_POST and $_GET or, preferred, check for a desired parameter in both locations.
You can invest endless time into stuff like this, but a convenient approach might look like this:
$param = isset($_GET['param']) ? $_GET['param']
: (isset($_POST['param']) ? $_POST['param']
: null);
This line is just an example. It retrieves a parameter called 'param' from the super globals $_GET or $_POST and stores it in the variable $params in the local scope. This way you can access any parameter you are looking for regardless if it is sent as a GET or as a POST parameter. I often wrap that in a convenience function which also takes care of validating the parameters runtime value.
You could also wrap this example in an iteration loop:
$params = [
'id' => null,
'key' => null,
'value' => null,
'remark' => null
]; // just as examples
foreach ($params as $key=>$null) {
// alternative 1: store the value of param $key in a single local scalar variable
// this results in local variables $id, $key, $value, $remark, just as examples
$$key = isset($_GET[$key]) ? $_GET[$key]
: (isset($_POST[$key]) ? $_POST[$key]
: null);
// alternative 2: store the value of param $key in a general but local params array
// this results in the above $params array, but filled with scalar values
$params[$key] = isset($_GET[$key]) ? $_GET[$key]
: (isset($_POST[$key]) ? $_POST[$key]
: null);
}
These are actually two examples. Obviously you need only one of the two statements shown inside the loop here. This depends on whether you prefer an array of params or separate local scalar variables.
If you are looking for a way to get all GET and POST parameters without actually knowing which that might be, then you have to combine the two super globals:
$params = array_merge($_GET, $_POST);
Note however that this is a very questionable architecture. It typically opens security holes.

Related

Check for the existence of any other POST variable that it is not the required one

I noticed (reading logs of websites I administer), hackers try to submit post requests, literally "inventing" post variables names.
Some website features old PHP code, eg.
if (isset($_POST["mail"]) && !empty($_POST["mail"])) {
//...
}else{
exit;
}
This basically checks if there is a $_POST variable "mail" and it is not empty.
Is it possible to check for the existence of any $_POST variable that it is NOT "mail" and exit the script in that case?
Use array_diff_key to check for differences:
$whitelist = ['mail' => null];
$hasOthers = !empty(array_diff_key($whitelist, $_POST));
I have a different way using filters and not accesing directly to $_POST.
At first, you have to create a definition of what $_POST elements you are interested in. So you have to create an array with the corresponding filters, as example for login definition
$definition = array(
["mail"] => FILTER_SANITIZE_EMAIL,
["passwd"] => FILTER_SANITIZE_STRING
);
Next you can filter all the desirable $_POST elements with filter_input_array
$desirablePost = filter_input_array(INPUT_POST, $definition);
And finalyly you can filter again all the $_POST values usign a filter constant (remembering that all $_POST elements are strings).
$allPost = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
So, to know if someone has injected another $_POST fields, we can compare the count() of both arrays.
if(count($desirablePost) !== count($allPost)){
//error or exit(1) ...
}

Is it possible to get empty array value via $_GET?

Is it possible to get empty array(array with 0 items) value via $_GET?
Is it possible with direct value setting?
count($_GET['param'])==0
You just need an empty value url = myform.php?param=&param2=
In form just let the value blank:
<input type='text' name='param' value ='' />
For an empty array:
url: myform.php?param[]=&param2[some_key]=
in form: <input type='text' name='param[]' value ='' />
From Ajax: (I remember this was so anti-intuitive and hard to search for):
ajax{
...
data: {'params[]':'','params2[some_key]':''}
}
Workaround:
Just edit the back-end and if there is no data for params or it is not an array (null, empty whatever ..) just assign an empty string to it:
$param = (isset($_GET['param']) && is_array($_GET['param']))? $_GET['param'] : array();
Update:
I did few tests and it seems there is no way to put "nothing" in the request ussing a form or ajax.
0, '', Null are valid values for the $_GET but empty array is not even created.
So to answer your question, it is NOT possible to get empty array value from the front-end.
There are few options to edit $_GET manually in the back-end:
<?php
if(!isset($_GET['param']) || !$_GET['param']){ //not set or (null,0,"")
$_GET['param'] = array();
}
if(count($_GET['param'])==0){...}; // 0 if no 'param' was provided.
If array is empty or containing values that doesn't matters. Just declare a variable and pass the $_GET[] to the variable.
for example,
$para=$_GET['param'];
and now
if(is_array($para))
{
//
}
else{
$para=new array();
}
passing empty array via GET is not possible under normal situation. That said, I can think of a really rare way that the checking you used will return true.
http://domain.com/receiver?param=a%3A0%3A%7B%7D
The above is basically a serialized and urlencoded empty array with the key 'param'
if the target server have some sort of filter that auto unserialize all incoming data, then it might happen.
(or something like the below)
foreach($_GET as $key => $value){
$_GET[$key] = unserialize($value);
}
count($_GET['param'])==0
I know this is a far fetch but it is possible, maybe some private test server that only handles serialized data but accidentally open to public e.t.c.
That said, it is still only passing a serialized empty array instead of a empty array itself. But let's be honest, this answer is more like a joke/fun answer that tries to point out under some very rare case
count($_GET['param'])==0
will return true (Without actively assigning values # server side)

define multiple results all at the same time in php

I have $config variable that have arrays inside it. In smarty I assign the variable like this:
$smarty->assign('config', $config);
when I call it, I used this : {$config.wateverarrayyouwant}
now I want to do the same thing with php. I want to define them in the same manner. How can I define all the arrays in $config in just one line?
I only know how to define a variable one at a time by using this :
define('wateverarrayyouwant', $config['wateverarrayyouwant']);
I tried changing wateverarrayyouwant to a variable because it can be any array :
define('$wateverarrayyouwant', $config[$wateverarrayyouwant]);
but the code above does not work. what is a good way to achieve what I want?
If you want to create a define for each key value pair in the array you can use:
<?php
foreach($config as $key => $value) {
define($key, $value);
}
I will note however that you cannot define array values, all define's must be scalar:
The value of the constant; only scalar and null values are allowed. Scalar values are integer, float, string or boolean values.
If you check the OP's answer for further explanation of what he's trying to achieve, it can be done with:
<?php
foreach($config as $key => $value){
$$key = $value;
}
?>
This question cannot be done. because I am trying to define a variable as a constant. I was just thinking about how can I reduce the letters for variables and never though that I better leave them alone. Logically, why do somebody need to change $config[$wateverarrayyouwant] to wateverarrayyouwant. I was only thinking about maintaining a neat code. but now I am thinking about it.. it is better to leave it as it is : $config[$wateverarrayyouwant]
This can be done with:
foreach($config as $key => $value){
$$key = $value;
}
You may not even want to use define here. define is used to create constants not plain variables and that carries with it certain connotations:
they are immutable for the life of the script
they must be scalar
If you just want an array variable then define it like normal with:
$whatever = array(
'key1' => 'value1'
);

Dynamically create variables in PHP

I want to create 1 variable name, but part of the name is the value stored in $i. Same for the GET result:
$Site.$i = $_GET['site'.$i]; // Should look something like $Site1 = $GET['site1'];
Please help me understand how to do this.
If you want a set of related variables, use an array:
$site[ $i ] = $_GET['site'.$i];
Even better, your GET parameters can also be an array
HTML
<input name="site[foo]" value="bar" />
PHP
$site = $_GET[ "site" ];
print_r( $site );
output
$site = array(
"foo" => "bar"
)
If you want the indexes for the array to decided automatically then you can do
<input name="site[]" value="foo" />
<input name="site[]" value="bar" />
<input name="site[]" value="baz" />
and get $_GET[ "site" ] out as
$site = array(
0 => "foo",
1 => "bar",
2 => "baz"
);
Direct Answer to Question
This is how you can do it. Not the best idea however.
$var = "$Site$i";
$$var = $_GET['site'.$i];
This makes use of variable variables.
Alternative Maintaining Current URL Structure
Alternatively perhaps something like this might work for you:
$vars = array();
foreach($_GET as $key => $value) {
if(0 === strpos($key, 'site')) { // Only grab value if the key is prefaced by the string 'site'
// You must sanitise the value some way here eg:
// $value = filter_var($value, FILTER_SANITIZE_STRING);
$vars[] = $value;
}
}
See filter_var() man page for more information on PHP filters and sanitisation/validation.
Revised URL Structure
I think this probably best solved however by making use of HTML arrays at the point your URL is generated. For more information on HTML arrays please see the PHP man page.
This allows you to access your information like the following:
$site1 = $_GET['site'][0];
$site2 = $_GET['site'][4];
This is the most logical method of dealing with this situation.
Update also see #Mat's answer for more information on this.
This is a bad idea for several reasons:
You have to loop through $_GET to find all variables (there's no language construct to pattern-match them)
Dynamic variables names are confusing, and may open security holes.
You will find that using an array will solve the second point, and also make it a lot easier to work with the code.
The first point can be solved by only using variable names you know. Send a variable containing a count how how many "sites" there are, for example:
site1=example&site2=example2&sitecount=2
This way you know that you only need to read site1 and site2, and you donät need to examine any other GET variables.
you van use $ as $_GLOBAL like this.
${'Site' . $i} = $_GET['site' . $i];
or you can use extract
please read the warnings about exract.
You can use variable variables like this:
$varname = $Site.$i;
$$varname = $_GET['site'.$i];
Doing this is discouraged however, because this is a huge security risk. You may write classes with fields representing your values from $_GET and validating them within the class.

wordpress / PHP - acessing post and get variables

Could anyone tell me why I am not retrieving info from a form I have submited within a wordpress template? The variables are being passed but they have no values?!?
New answer to an age-old question!
I came across this post, which didn't help, and wrote my own utility (happily shared and feel free to improve)
/* Get Parameters from $_POST and $_GET (WordPress)
$param = string name of specific parameter requested (default to null, get all parameters
$null_return = what you want returned if the parameter is not set (null, false, array() etc
returns $params (string or array depending upon $param) of either parameter value or all parameters by key and value
Note: POST overrules GET (if both are set with a value and GET overrules POST if POST is not set or has a non-truthful value
All parameters are trimmed and sql escaped
*/
function wordpress_get_params($param = null,$null_return = null){
if ($param){
$value = (!empty($_POST[$param]) ? trim(esc_sql($_POST[$param])) : (!empty($_GET[$param]) ? trim(esc_sql($_GET[$param])) : $null_return ));
return $value;
} else {
$params = array();
foreach ($_POST as $key => $param) {
$params[trim(esc_sql($key))] = (!empty($_POST[$key]) ? trim(esc_sql($_POST[$key])) : $null_return );
}
foreach ($_GET as $key => $param) {
$key = trim(esc_sql($key));
if (!isset($params[$key])) { // if there is no key or it's a null value
$params[trim(esc_sql($key))] = (!empty($_GET[$key]) ? trim(esc_sql($_GET[$key])) : $null_return );
}
}
return $params;
}
}
Just came up against the same/similar issue; it is not ideal to use get variables on Wordpress as the URL is structured using mod_rewrite and has some reserved query parameters. The Wordpress Docs on query vars gives you a bit of a list, but it is not comprehensive.
In summary, the variables you were using may have been one of those reserved or modified or handled by Wordpress?
(I know this is an old question but it needs an answer or clarification.)
Please check form method
<form name="frmlist" method="post">
Try with this
print var_dump($_GET);
print var_dump($_POST);

Categories