I generate several forms with different <input> name attributes and I can not exactly define all input-names for fetching them after posting.
How can I receive ALL $_POST data from the form (without having a name-attribute) and put them in an array like that:
'name_attribute' => 'value'
A basic loop will do this:
$post = array();
foreach ($_POST as $key => $value) {
$post[$key] = $value;
}
I don't know how this benefits you though as all you have done is remake your $_POST superglobal.
With any POSTs, php puts it into the array $_POST. You can treat this like any array and just loop through each key/value of the POST.
$your_array = array();
foreach ($_POST as $key => $val){
$your_array[$key] = $val;
}
to make this more secure, I would suggested escaping the $val by using other php functions such as mysql_real_escape_string(), trim(), htmlspecialchars().
Try this code
$post = $_POST;
foreach($post as $name => $value)
{
echo $name." = ".$value;
}
$_POST is an associative array in the format
'field_name' => 'field_value'
Related
I'm building a webhook that will receive data from an external service.
In order to retrieve data, I'm using the following array:
$data = [
$_POST['aaa'],
$_POST['bbb'],
$_POST['ccc'],
$_POST['ddd'],
$_POST['eee']
];
Is it possible to build the same array without repeating $_POST? I mean something like:
$data = $_POST [
['aaa'],
['bbb'],
['ccc'],
['ddd'],
['eee']
];
Obviously, that code is wrong.
Thanks.
There's no shortcut like that. You could use array_map():
$data = array_map(function($key) {
return $_POST[$key];
}, ['aaa', 'bbb', 'ccc', ...]);
$data = $_POST
This will build your new $data array the same way as your GLOBAL $_POST array including the POST Key names and their assigned values.
Also checkout extract($_POST), as this will extract each key to its same name variable, which may be easier to then reference in your web-hook or any functions or procedural code you uses from then on. This essentially does this:
$aaa = $POST['aaa']
$bbb = $POST['bbb']
$ccc = $POST['ccc']
etc etc
https://www.php.net/manual/en/function.extract.php
The simplest way for me would be:
For getting all the values in the $_POST array
foreach($_POST as $value){
$data[] = $value;
}
For getting all the values and want to keep the key
foreach($_POST as $key=>$value){
$data[$key] = $value;
}
For getting a specific array of values from the array
foreach(['aaa','bbb','ccc','ddd','eee'] as $column){
$data[] = $_POST[$column];
}
Just a good idea to always escape variables ;)
$con = mysqli_connect('hostcleveranswer.com','USERyouearn','PWDanupv0Te','dropthemicDB')
foreach($_POST as $key => $value) {
$data[] = mysqli_escape_string($con,$value);
}
//i feel that was a good simple answer using tools without having to a learn a new function syntax
I have read a lot of posts and have not been able to find a solution to my issue.
I have a $_POST array named "Water", $_POST['Water'] and its contents are:
[Water] => Array ( [0] => 55.0 [1] => 22 )
Is it possible to use the name of the post inside a foreach loop so the $key could use the name "Water":
foreach($_POST['Water'] as $key => $val) {
$fields[] = "$field = '$val'";
//echo "Key: $key, Value: $val<br/>\n";
}
Many thanks for your time.
Not really. foreach() operates on the contents of an array. Whatever actually contains that array is outside of foreach's view. If you want to dynamically use the Water key elsewhere, you'll have to do that yourself:
$key = 'Water'
foreach($_POST[$key] as $val) {
$fields[] = "$key = '$val'";
}
If I read this right you basically want $field='water' inside the foreach. This can be done be rethinking the way we build the foreach.
You simply need to make the field value a variable and pass use that rather everywhere the value is needed.
$field = 'Water';
foreach($_POST[$field] as $key => $val) {
$fields[] = "$field = '$val'";
//echo "Key: $key, Value: $val<br/>\n";
}
The advantage of this approach is that if you change your mind and the $_POST key is later called, "liquid" one single line needs to be edited and that is all. Furthermore, if your foreach were part of a function $field could be a function parameter. In a roundabout way, you are actually getting pretty close to some code reuse principles.
Upon posting a form using _GET I would like to get the input name
See below part of url upon submit
.php?14=0&15=0&16=0&17=0&18=0&19=0
I know how to get the variable E.G:
$14=$_GET["14"];
Which is 0
However is it possible to do this and get the input name (eg 14) and then turn these into variables? (To save the input name to the DB)
To get all the $_GET parameters, you can do:
foreach($_GET as $key => $value){
echo "Key is $key and value is $value<br>";
}
This will output each key (14, 15, 16 etc) and value (0, 0, 0 etc).
To bind a variable name with a variable string, look at variable variables:
foreach($_GET as $key => $value){
$$key = $value;
}
As a result, you will have the following variables with the following values:
$14 = 0;
$15 = 0;
$16 = 0;
// etc...
Alternatively (as you don't necessarily know what the key/value pairs would be), you could create an empty array and add these keys and values to it:
foreach($_GET as $k => $v){
$arr[$k] = $v;
}
The resulting array will be:
$arr[14] = 0;
$arr[15] = 0;
$arr[16] = 0;
// etc...
Solution using single loop (Update):
If you're just using question/answer single time you can do it in single loop like this,
<?php
foreach($_GET as $key => $value){
$question = $key;
$answer = $value;
// Save question and answer accordingly.
}
If you will be using question answer to perform other things, use the following method.
You can get all the keys using array_keys(), where $_GET is an array.
Use it like this,
<?php
$keys=array_keys($_GET);
print_r($keys); // this will print all the keys
foreach($keys as $key) {
// access each key here with $key
}
Update:
You can make a pair of question,answer array and put it in the main array to insert it in the database like this,
<?php
$mainArray=array();
$keys=array_keys($_GET);
foreach($keys as $key) {
// access each key here with $key
$questionAnswerArray=array();
$questionAnswerArray["question"]=$key;
$questionAnswerArray["answer"]=$_GET[$key];
$mainArray[]=$questionAnswerArray;
}
// Now traverse this array to insert the data in database.
foreach($mainArray as $questionanswer) {
echo $questionanswer["question"]; //prints the question
echo $questionanswer["answer"]; // prints the answer.
}
I am trying to figure out how I can handle possible duplicate array keys.
I have this form with a select dropdown which can select multiple options (more than 1). And I am using jQuery.serialize() to serialize the form on submit.
The serialized string for a multi-select element would look like so:
select=1&select=2&select=3 // assumming I selected first 3 options.
Now in the PHP side, I have the following code to handle the "saving" part into a database.
$form_data = $_POST['form_items'];
$form_data = str_replace('&','####',$form_data);
$form_data = urldecode($form_data);
$arr = array();
foreach (explode('####', $form_data) as $part) {
list($key, $value) = explode('=', $part, 2);
$arr[$key] = $value;
}
Ok this all works for the rest of the form elements but when it comes to the select element, it only picks the last selected key/value pair. So my array now looks like this:
Array ( [select_element] => 3)
What I need, is for it to look like:
Array ( [select_element] => '1,2,3')
So I guess what I am asking is based on my code, how can I check if a key already exists and if it does, append to the $value.
If you can modify the client-side code, I would rather change the name of the select to select[], that way it will be parsed as an array in your server script.
You can't have multiple keys with the same name... They're unique keys. What it's doing is setting select = 1, then select = 2, then select = 3 and you end up with your final value of 3.
If you want to allow multiple choices in your select menu, you should change the name of the element so that it submits that data as an array, rather than multiple strings:
<select name="select[]" multiple="multiple">
which should result in something like this instead:
select[]=1&select[]=2&select[]=3
and when PHP requests that data, it will already be an array:
$data = $_POST['select'];
echo print_r($data); // Array(1, 2, 3)
PHP has its own way of encoding arrays into application/x-www-form-urlencoded strings.
PHP's deserialization of x-www-form-urlencoded is implemented by parse_str(). You can think of PHP as running these lines at the beginning of every request to populate $_GET and $_POST:
parse_str($_SERVER['QUERY_STRING'], $_GET);
parse_str(file_get_contents('php://input'), $_POST);
parse_str() creates arrays from the query string using a square-bracket syntax similar to its array syntax:
select[]=1&select[]=2&select[]=3&select[key]=value
This will be deserialized to:
array('1', '2', '3', 'key'=>'value');
Absent those square brackets, PHP will use the last value for a given key. See this question in the PHP and HTML FAQ.
If you can't control the POSTed interface (e.g., you're not able to add square-brackets to the form), you can parse the POST input yourself from php://input and either rewrite or ignore the $_POST variable.
(Note, however, that there is no workaround for multipart/form-data input, because php://input is not available in those cases. The select=1 and select=2 will be completely and irretrievably lost.)
Ok, I was able to resolve this issue by using the following code:
if (array_key_exists($key, $arr)) {
$arr[$key] = $arr[$key].','.$value;
} else {
$arr[$key] = $value;
}
So now the loop looks like this:
foreach (explode('####', $form_data) as $part) {
list($key, $value) = explode('=', $part, 2);
if (array_key_exists($key, $arr)) {
$arr[$key] = $arr[$key].','.$value;
} else {
$arr[$key] = $value;
}
}
This will essentially string up the value together separated by a comma which can then be exploded out into an array later.
You should change your client-side code to send the augmented value: array.join(","); and use that in your PHP side. Because when your data reaches your script, the other values have already been lost.
This should give you the solution you require
$form_data = str_replace('&','####',$form_data);
$form_data = urldecode($form_data);
$arr = array();
foreach (explode('####', $form_data) as $part) {
list($key, $value) = explode('=', $part, 2);
if (isset($arr[ $key ])) {
$arr[$key] = ','.$value;
} else {
$arr[$key] = $value;
}
}
I want to strip HTML code from multiple fields. So I used:
extract($_POST)
Then an insertion into the table.
I won't strip each field like:
$user = strip_tags($user);
$email = strip_tags($email);
.....
There is any solution to strip my extract($_POST) array?
The same for mysql_real_escape_string()
EDIT 1
I won"t use
foreach($_POST as $key => $value){
$_POST[$key] = mysql_real_escape_string(strip_tags($value));
}
I want to use the short variable:
$name, $email
not:
$_POST['name'] , $_POST['email']
And without extract() as is deprecated.
Edit 2 the solution is:
foreach($_POST as $key => $value){
$$key = mysql_real_escape_string(strip_tags($value));
}
You can use array_map() to specify a callback function to each element of a given array.
$_POST = array_map("strip_tags", $_POST);
Edit: Maybe you should specify why you're attempting to escape user input. For example, PHP has specific aids for escaping values that will be added to the database and also for values that will be displayed on the page. As the former could result in an SQL injection and the latter an XSS vulnerability.
I guess you want this piece of code
foreach($_POST as $key => $value){
$$key = strip_tags($value);
}
//The insertion here
insertion();
Old
foreach($_POST as $key => $value){
$_POST[$key] = strip_tags($value);
}
extract($_POST);
//The insertion here
insertion();
After that you have all the post fields strip_tagged
Use the filtering functions that PHP provides, specifically in this case you would be interested in filter_input_array:
$filtered = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRIPPED);