$_POST metacharacters? - php

in my $_POST, I have a variable whose name changes. the name is modify_0, but the number at the end changes depending on the button that was pressed.
Is there anyway to check what the number is for that variable in $_POST?
Say:
$_POST['modify_(check for number or any character)']

You would need to iterate over all of the keys within the $_POST variable and take a look at their format:
$post_keys = array_keys( $_POST );
foreach($post_keys as $key){
if ( strpos($key, 'modify_' ) != -1 ){
// here you know that $key contains the word modify
}
}

Besides the correct answers given above, I would recommend changing your code slightly so it's easier to work with.
Instead of having inputs with the format:
// works for all types of input
<input type="..." name="modify_1" />
<input type="..." name="modify_2" />
You should try:
<input type="..." name="modify[1]" />
<input type="..." name="modify[2]" />
This way, you can iterate through your data in the following way:
$modify = $_POST['modify'];
foreach ($modify as $key => $value) {
echo $key . " => " . $value . PHP_EOL;
}
This works especially well for multiselects and checkboxes.

Try something like this:
// First we need to see if there are any keys with names that start with
// "modify_". Note: if you have multiple values called "modify_X", this
// will take out the last one.
foreach ($_POST as $key => $value) {
if (substr($key, 0) == 'modify_') {
$action = $key;
}
}
// Proceed to do whatever you need with $action.

Related

submit form data from a foreach loop

I have a foreach loop with a form inside for each result like so:
foreach($this->results() as $that) {
<form>
<input type="text" name="name[]">
<input type="text" name="this[]">
</form>
}
and so on. My question is how do I each forms data. I understand you can do something like the following:
$_POST['name'][0];
$_POST['name'][1];
etc, but is their a way to get this done without knowng how many forms their will be. I mean like foreach loop the $_POST data and get each form?
Many thanks
foreach ($_POST['name'] as $val) { /* do what you want, want you want with my value */ }
$_POST['name'] is just an array. Use count or any array function you want on it then.
You can do it like this:
foreach ($_POST['name'] as $val => $value) {}
assuming these rows are being generated by a while loop, and the variable is named like this
$val = $row['val'];
And then in your form you'd have something like this:
echo '<input type="hidden" value="'.$val.'" name ="val[]" /><input type="text" name="name['.$val.'] />";
basically the name variable would be identified by the value itself being generated but also appended on a named variable, and then can be fed into your foreach.
foreach ($_POST['name'] as $key => $value) {
echo 'key: '.$key.' Value : '.$value;
}
--------------------------
output key: 0 Value : nameValue1
key: 1 Value : nameValue2
$_POST['name'] is an array, if you get multiple value with key, just get with foreach value

PHP post all form inputs without creating variables for each

Usually when I use PHP I create a variable and post statement for each form input like so:
$myVar1 = $_POST["formItem1"];
$myVar2 = $_POST["formItem2"];
ect......
I know if i use:
echo $_POST;
I can get all the key and values from the form inputs but I don't know how to use them in a script.
So I guess I have 2 questions:
How do I quickly post all form inputs without creating a variable for each input?
How do I use a posted in a script without having it assigned to a specific variable?
To simply echo all the inputs, you can use a foreach loop:
foreach ($_POST as $key => $value) {
echo $value.'<br/>';
}
If you don't want to store them in variables, use arrays:
$data = array();
foreach ($_POST as $key => $value) {
$data[] = $value;
}
Now, $data is an array containing all the data in $_POST array. You can use it however you wish.
You don't have to assign to a variable. You can use directly $_POST['input_name']
If you want to deal with each sended params, you can use foreach loop:
foreach ($_POST as $key => $val)
{
echo "$key : $val <br/>";
}
for this instance of just quickly checking and testing i typically just use the print_r() function: documentation here
as quoted from the docs:
print_r() displays information about a variable in a way that's readable by humans.
one line easy to toggle on and off (with comments)- no need to use any form of variables
print_r($_POST);
if i need my output nice and readable i like to expand it as follows:
function print_r2($x){
echo '<pre>';
print_r($x);
echo '</pre>';
}
and then you can call with: print_r2($_POST);
this way you get the pre-formatted text block on your html page and can see the line breaks and tabbed spacing provided from the $_POST object printout
Another way to extract (besides the extract function) variables is;
$array = array('foo'); // Which POST variables do you want to get
foreach($array as $key) {
if(!isset(${$key})) { // Check if variable hasn't been assigned already
${$key} = $_POST[$key];
}
}
echo $foo;
I would not recommend it because it can get quite messy to keep up.
View everything in $_POST is useful for debugging
echo '<pre>'.print_r($_POST, true).'</pre>';
Access a specific checkbox
HTML
<input type="checkbox" value="something" name="ckbox[]" checked>
<input type="checkbox" value="anotherthing" name="ckbox[]" checked>
PHP
echo $_POST['ckbox'][0]; // something
echo $_POST['ckbox'][1]; // anotherthing
// isolate checkbox array
$ckbox_array = $_POST['ckbox'];
Define a function that allows you to access a specific $_POST item by name (key):
function get_post_value($name, $default)
{
if ( isset($_POST[$name]) ) {
return $_POST[$name];
} else if ( $default ) {
return $default;
}
return null;
}
$default allows you to pass a value that can be used as a fallback if the key you specify isn't present in the $_POST array.
Now you can reference $_POST items without assigning them to a variable, and without worrying if they are set. For example:
if ( get_post_value('user-login-submit', false) ) {
// attempt to log in user
}
You can use extract($_POST), it will create variables for you.
For example, you can have for the code you posted :
<?php
$_POST["formItem1"] = "foo";
extract($_POST);
echo $formItem1; // will display "foo"
?>
EDIT : it's not PHP explode, it's extract.

How do I exclude hidden field from PHP foreach loop

I have a simple form that inserts data into a database using foreach($_POST as $key=>$value) I have a hidden field on the form
<input name="isset" type="hidden" value="true" />
And i use if(isset($_POST['isset'])) {
I'm trying to work out how to exclude the hidden field from the loop ...?
I've looked at this post but don't understand where i would use if (strpos($key, 'hdn_') == false) // proceed
How to exclude <input type="hidden"> from a for each loop in PHP
any guidance would be appreciated....
If you know the exact names of keys you want to exclude, array_diff_key is a convenient option:
$keysToRemove = array('isset'); // you can add as many as you want
$values = array_diff_key($_POST, array_flip($keysToRemove));
foreach ($values as $k => $v) { ... }
However, since $values is intended to go into the database you should use a whitelist of allowed keys instead of a blacklist. You can do that with array_intersect_key:
$keysToKeep = array('field1', 'field2', 'field3'); // as many as you want
$values = array_intersect_key($_POST, array_flip($keysToKeep));
foreach ($values as $k => $v) { ... }
Inside the foreach:
foreach ($_POST as $key => $value) {
if ($key != 'isset') {
//code here
}
}
(For what I got from your question)
Or from your array, you can unset() the element with the 'isset' array key.

Cleaning up array elements from a form

I have a form that uses inputs to create and array. The inputs are not all required but at least one is.
<form method="post" action="process.php">
<input type="text" name="MAC[]" maxlength="12" />
<input type="text" name="MAC[]" maxlength="12" />
<input type="text" name="MAC[]" maxlength="12" />
<input type="text" name="MAC[]" maxlength="12" />
<input class="submitbg" type="submit" value="Register" name="submit"/>
</form>
Now on process.php I want to loop through the array remove two types of special characters : ; then make all upper case, and verify there are only 12 characters and then serialize the arrray.
$my_array = $_POST['MAC'];
foreach ($my_array as $val){
$val = strtoupper($val);
$val = str_replace(";","",$val);
$val = str_replace(":","",$val);
$val = trim($val);
if (strlen($val) != 12)){
$valid = false;
$error = "Your MAC address is not 12 characters long";
}
}
$mac_addresses = serialize($my_array);
// if valid is not false do something with the cleaned up array.
The questions:
Will my foreach loop save the updated values back into the array?
How to check to make sure there is at least one array value?
I am just not sure if my foreach loop updates and resaves the values each time
If you want to save the values you should change your loop so that it looks something like this:
foreach ($my_array as $idx => $val) {
...
$my_array[$idx] = $val;
}
Of course you could also save the proper value to a separate clean array which you will then use further on in your application.
I also have to check to make sure there is at least one entry.
In theory you do not have to check whether the array contains elements to use the array in a foreach. The thing you need to check though is whether the variable contains an array. Suppose the MAC[] field wasn't submitted to the server you would first get a warning (it might also be an error nowadays) because you are looking up some non-existent index in the array. Secondly you would get an error on your foreach as it works on arrays (or anything that is Traversable). You could fix this with the following check:
if (!empty($_POST['MAC'])) {
$my_array = $_POST['MAC'];
if (!is_array($my_array)) {
// throw some error.
}
}
Of course you would want to do this validation of your input in a more structured way by providing a validation framework which you can provide validation rules and some input and the validation framework will then handle the validation and most importantly the error messages for you.
Actually could also change the last if-statement to read:
if (!is_array($my_array) && !($my_array instanceof Traversable))
That is if you want to be sure $my_array contains something you can traverse over with foreach. The nasty bit is that the built-in array() isn't Traversable, nasty although understandable.
What's the question?
you can do str_replace(array(';',':'),'',$val);
It's usually better to trim before doing other processing on the same variable due to the overhead involved in processing data you will eventually cut
Consider using break on errors, if you halt execution on one error.
You're not really doing any updates to $my_array.
Consider doing:
foreach($my_array as &$val)
You pass by reference so all updates to $val happen to the actual array. Or:
foreach($my_array as $key=>$val){
$my_array[$key]=trim($my_array[$key]);
You can also try to create a new array for your sanitized data and then over-write your old array. It all depends on needs.
I'm also not understanding your question /problem.
But, looking at your code, you might get the feeling that in the end nothing has happened to your POSTed vars.
You're right! :-)
Your cleaned up array at the end of the script is exactly the original array.
You might want to achieve something like this: The clean array will contain cleaned values, if they consist of 12 characters.
$my_array = $_POST['MAC'];
$my_clean_array = $_POST['MAC'];
foreach ($my_array as $val) {
$val = strtoupper($val);
$val = str_replace(";","",$val);
$val = str_replace(":","",$val);
$val = trim($val);
if (strlen($val) != 12)) {
$valid = false;
$error = "Your MAC address is not 12 characters long";
}
else {
$my_clean_array[] = $val;
}
}
$mac_addresses = serialize($my_clean_array);
To check to see if you have at least one you should be able to use if(count($my_array) > 1)

How do I return specific keys from the $_POST array?

I would like to check to see if there are any keys in $_POST that contain a string. The string will not be the full key, only part of the key. (ie. search string = "delRowID", $_POST key = "delRowID_16"). I have tried to use array_keys($_POST,"delRowID"), but it has never returned anything.
CODE
print_r($_POST);
print_r(array_keys($_POST,"delRowID"));
RETURNS
Array ( [delRowID] => 29 [qAction] => [elmUpdateId] => [elmTtl] => [elmDesc] => [elmStr] => ) Array ( )
If this is being sent by a form, considering naming the elements as array elements. For example,
<input type="checkbox" name="delRowID[16]" />
<input type="checkbox" name="delRowID[17]" />
would come in as an array named $_POST['delRowID'] with elements for each valid input.
However, this is a contrived example which works better with other input types.
For checkboxes, it would be better done like this, which creates an array with a value for each successful checkbox that you can easily loop over:
<input type="checkbox" name="delRowID[]" value="16" />
<input type="checkbox" name="delRowID[]" value="17" />
See Also: How do I create arrays in a HTML <form>?
Do a loop using array_keys() and check the key with strpos()
foreach (array_keys($_POST) as $key) {
if (strpos($key, 'delRowId') === 0) {
echo $key." found!";
}
}
Loop through the keys provided to you by array_keys($_POST). Do a string match on each.
Also, note that array_keys($_POST,"delRowID") searches for keys that are associated with a value of "delRowID".
Because you are searching for partial text, you can loop through it:
foreach($_POST as $key => $value)
{
if (strpos($key, 'delRowID') !== false)
{
echo $key;
break;
}
}
Just another way (extending mads answer):
if( getKey( 'delRowId', $_POST ) ){
// delRow?
}
function getKey($stringToFind, $array) {
foreach ($_POST as $key => $val) {
if (strpos($stringToFind, $key) !== false) {
return $val;
}
}
return false;
}

Categories