Cleaning up array elements from a form - php

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)

Related

Dynamic form and looping through form array to insert into Mysql

I have a form that is built dynamically:
foreach($xml->config->popup as $popup_item){
<input class="fm-req" id="fm-popup_name[]" name="fm-popup_name[]" type="text" value="" />
<textarea class="fm-req" rows="4" cols="50" id="fm-popup_desc[]" name="fm-popup_desc[]" /></textarea>
<input class="fm-req" id="fm-popup_image[]" name="fm-popup_image[]" type="file" />
}
I haven't worked with arrays in form names before but i seen on another post on stack overflow you could do this and it seems like this is a much better way than i had planned, which was to add $i to the end of the name and increment each loop so i would have ended up with:
fm-popup_name1
fm-popup_name2
fm-popup_name3 etc etc
I could then do a loop count when building the form, pass the count as a hidden field and then use a for loop where x <= count and do my insert that way. But in the interest of improving the code and keeping it more compact and easy to understand, i think its worth doing this way but i cant figure out a good way to do it:
foreach($_POST['fm-popup_name'] as $index => $value) {
// get the value of name
}
foreach($_POST['fm-popup_desc'] as $index => $value) {
// get the value of name
}
foreach($_POST['fm-popup_image'] as $index => $value) {
// get the value of name
}
With that i can access all the data i need but i don't want to make 3 separate inserts for 1 record.
How can i take the information above and something like:
foreach($_POST['fm-popup_name,fm-popup_desc,fm-popup_image'] as $index => $value) {
INSERT INTO mytable(
popup_name,
popup_desc,
popup_image
)
VALUES(
'$popup_name',
'$popup_desc'
'$popup_image'
)";
}
Any ideas? Hopefully code is ok, i filtered out all the other crap that is irrelevant so hopefully all the id's etc match but im just looking for a rough example and i can convert back to my code.
You can use something the following, but there is a risk (can you spot it?) :
$entries = count($_POST['fm-popup_name']);
for($i = 0; $i < entries; ++$i) {
$name = $_POST['fm-popup_name'];
$desc = $_POST['fm-popup_desc'];
// other processing
}
If you haven't spotted it, the risk is that not all array elements may be populated, so you may not get a proper mapping for each row, unless you enforce it on the front end and validate this before processing your loop.

$_POST metacharacters?

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.

Arrays in php and input arrays

I wanted to make sure I am adding using these arrays correctly, could someone please go over my code and clarify. I have tried printing the array and nothing is displaying.
HTML
Start Date: <input type="text" name="start_date[]"/>
End Date: <input type="text" name="end_date[]"/>
Description:<textarea name="position[]"></textarea>
PHP
initializeArrays(); // Initialize arrays
$_SESSION['start_date_array'][] = $_GET['start_date[]']; // Add html input arrays to a session array.
$_SESSION['end_date_array'][] = $_GET['end_date[]'];
$_SESSION['position_array'][] = $_GET['position[]'];
$_SESSION['submit_employment_message'] = 'Thank you for the submission';
I want to set the array I am getting to my session array. Essentially I am expecting there to be multiple start dates. Being submitted to the PHP page. For example there could be multiple of start dates inputted. Please let me know if you need any clarification.
Thank you for the help!
I think you want:
$_SESSION['start_date_array'] = $_GET['start_date'];
$_SESSION['end_date_array'] = $_GET['end_date'];
$_SESSION['position_array'] = $_GET['position'];
Form fields that have [] appended to their name are assumed to be arrays
You can make foreach on $_GET and retrieve key=value
foreach ($_GET as $key => $value) {
$_SESSION[$key] = $value;
}
and retrieve the name of the sessions by the key of $_GET

moving a numbered amount of named items from one array into another

I'm not exactly sure how the logic would work on this. My brain is fried and i cant think clearly.
I am handling some POST data, and one of the fields in this array is a quantity string. I can read this string and determine if there are more than 1 widgets that need handled.
if($quantity <= 1){ //$_POST[widget1] }
Now say there are 4 widgets. The quantity field would reflect this number, but how would i loop through them and assign them to a new array themselves?
$_POST[widget1], $_POST[widget2], $_POST[widget3], $_POST[widget4]
How do i take that quantity number, and use it to grab that many and those specific named items from the post array, using some kind of wild card or prefix or something? I dont know if this is a for, or while, or what kind of operation. How do I loop through $_POST['widget*X*'], where X is my quantity number?
The end result is im looking to have an array structured like this:
$widgets[data1]
$widgets[data2]
$widgets[data3]
$widgets[data4]
Using a for loop, you can access the $_POST keys with a variable, as in $_POST["widget$i"]
$widgets = array();
for ($i=1; $i<=$quantity; $i++) {
// Append onto an array
$widgets[] = $_POST["widget$i"];
}
However, a better long-term solution would be to change the HTML form such that it passes an array back to PHP in the first place by adding [] to the form input's name attribute:
<input type='text' name='widgets[]' id='widget1' value='widget1' />
<input type='text' name='widgets[]' id='widget2' value='widget2' />
<input type='text' name='widgets[]' id='widget3' value='widget3' />
Accessed in PHP via $_POST['widgets'], already an array!
var_dump($_POST['widgets']);
Iterate over the number of items, at least over one (as you describe it):
$widgets = array();
foreach (range(1, max(1, $quantity)) as $item)
{
$name = sprintf('widget%d', $item);
$data = sprintf('data%d', $item);
$widget = $_POST[$name];
// do whatever you need to do with that $widget.
$widgets[$data] = $widget;
}

PHP: translate POST into simple variables?

I know this is totally wrong, I didn't write the app, I just have to make it work while I work on the new one. Seems like GoDaddy made some updates to our account so now there are some things that don't work. I already turned register globals on and a lot of things went back to normal. Now, this doesn't work...
There is a hidden field <input type="hidden" name="SUBMIT1" value="1" />
There is a check for that field
if($SUBMIT1) {
// this part never gets executed.
}
I know I can easily fix it by doing this instead...
if($_POST['SUBMIT1']) {
// this part never gets executed.
}
The problem is, this is a huge app and it's going to take a loooong time to do that everywhere. Is there a way or a setting I can turn on so that when a form is submitted $_POST['WHATEVER'] also works as $WHATEVER?
You can use extract to get the exact functionality you described:
extract($_POST);
Please note the possible safety issue here: a user could send extra data in $_POST and "overwrite" the values of existing variables in your code. You can pass a second parameter to extract to prevent these problems:
extract($_POST, EXTR_SKIP);
This will skip extracting any fields in the $_POST array that already have matching variables in the current scope.
you can try something like this:
$_POST = array('SUBMIT1' => 'SUBMIT ONE', 'SUBMIT2' => 'SUBMIT TWO');
foreach($_POST as $k => $v) {
define(''. $k. '', $v);
}
echo SUBMIT1; // and so on
foreach ($_POST as $key => $value ) {
if(is_array($value)){
foreach ($value as $k => $v ) {
$$k = $v ;
}
}else{
$$key=$value;
}
echo $key ." : " .$value."<br>";
}

Categories