How to validate these elements in PHP? - php

I have checkboxes with the following names:
chk-cloud-a
chk-cloud-b
and so on...
chk-dco-a
chk-dco-b
and so on...
How do I validate after form submission such that:
Atleast one element from the checkboxes with name starting with chk-cloud or chk-dco must be ticked?
I hope someone can help me with this.
Cheers!

If they're checkboxes then all you really care about is whether or not they have a value. What that value is is not significant.
All you need to do is check that there are elements in the $_GET or $_POST (depending on form submission method) that contain fields of that name.
if (array_key_exists ('chk-cloud-a ', $_POST)) {
// Do what should happen of that checkbox is checked
}
If the problem is that you have multiple similar checkboxes then you might want to consider grouping them together in an array. This is done by using square bracket notation in the field name:
<input type="checkbox" value="1" name="chk-cloud[a]" />
<input type="checkbox" value="1" name="chk-cloud[b]" />
<input type="checkbox" value="1" name="chk-cloud[c]" />
<input type="checkbox" value="1" name="chk-cloud[d]" />
You can use a loop to process such a group
foreach ($_POST [chk-cloud] as $key => $value) { // We're really only interested in the key
handleCheckbox ($key) // handleCheckbox is some function you've wrote
}
Or
foreach (array_keys ($_POST [chk-cloud]) as $key) { // Logically the same as above

Just use preg_match or strpos to check if any key in POST matches Your requirements. Personally i would make subarray of these elements and just check if its empty.

try like this:
function checkBoxValidate(){ //method to test checkbox
$array = array('a','b','c','d', ....); // make array for each checkbox name
foreach ($array as $a){
if((isset($_REQUEST['chk-cloud-'.$a]) || isset($_REQUEST['hk-dco-'.$a])) && ($_REQUEST['chk-cloud-'.$a] == 'check_value' || $_REQUEST['hk-dco-'.$a] == 'check_value' ) ){
return true;
}
}
return false; //return no check box was checked
}

Related

PHP How to process a form that has dynamically generated fields?

I am trying to process a form which I don't know ahead of time what the form fields will be. Can this still be done in PHP?
For example I have this html form:
<form method="post" action="process.php">
<?php get_dynamic_fields(); // this gets all the fields from DB which I don't know ahead of time what they are. ?>
<input type="submit" name="submit" value="submit" />
</form>
And here is what I have in the PHP process file
<?php
if ( isset( $_POST['submit'] ) && $_POST['submit'] === 'submit' ) {
// process form here but how do I know what field names and such if they are dynamic.
}
?>
Here is a caveat: assuming I can't get the data from the db ahead of time, is there still a way to do this?
Sure, just iterate over all the items in the $_POST array:
foreach ($_POST as $key => $value) {
// Do something with $key and $value
}
Note, your submit button will exist in the array $_POST, so you may want to write some code to handle that.
You can iterate over all $_POST keys like this.
foreach($_POST as $key => $value)
{
echo $key.": ".$value;
}
This will give you the field names used in HTML form.
$field_names = array_keys($_POST);
You can also just iterate through the POST array using
foreach($_POST as $field_name => $field_value) {
// do what ever you need to do
/* with the field name and field value */
}
you could loop over all parts of the `$_POST array;
foreach($_POST as $key => $value){
//$key contains the name of the field
}
Get the names of the fields from your get_dynamic_fields function and pass them in a hidden input that is always an array with a static name. Then parse it to get the names of the inputs and how many there are.

PHP avoiding a long POST

This is more of a technique question rather than maybe code. I am having a php form with many fields (items to select). Naturally some of the items might be selected and some not. How do I know which ones are selected when i post the data from page 1 to page 2? I thought of testing each one if empty or not, but there are just too many fields and it doesn't feel at all efficient to use or code.
Thanks,
UPDATE EDIT:
I've tried the following and maybe it will get me somewhere before I carry on testing the repliers solutions...
<html>
<body>
<form name="test" id="name" action="testprocess.php" method="POST">
<input type="text" name="choices[shirt]">
<input type="text" name="choices[pants]">
<input type="text" name="choices[tie]">
<input type="text" name="choices[socks]">
<input type="submit" value="submit data" />
</form>
</body>
</html>
and then second page:
<?php
$names = $_POST['choices'];
echo "Names are: <br>";
print_r($names);
?>
This gives out the following:
Names are: Array ( [shirt] => sdjalskdjlk [pants] => lkjlkjlk [tie]
=> jlk [socks] => lkjlkjl )
Now what I am going to try to do is iterate over the array, and since the values in my case are numbers, I will just check which of the fields are > 0 given the default is 0. I hope this works...if not then I will let you know :)
I think what you're looking for is this:
<form action="submit.php" method="POST">
<input type="checkbox" name="checkboxes[]" value="this" /> This
<input type="checkbox" name="checkboxes[]" value="might" /> might
<input type="checkbox" name="checkboxes[]" value="work" /> work
<input type="submit" />
</form>
And then in submit.php, you simply write:
<?php
foreach($_POST['checkboxes'] as $value) {
echo "{$value} was checked!";
}
?>
The square brackets in the name of the checkbox elements tell PHP to put all elements with this name into the same array, in this case $_POST['checkboxes'], though you could call the checkboxes anything you like, of course.
You should post your code so we would better understand what you want to do.
But from what I understood you are making a form with check boxes. If you want to see if the check boxes are selected, you can go like this:
if(!$_POST['checkbox1'] && !$_POST['checkbox2'] && !$_POST['checkbox3'])
This looks if all the three check boxes are empty.
Just an idea:
Create a hidden input field within your form with no value. Whenever any of the forms fields is filled/selected, you add the name attribute of that field in this hidden field (Field names are saved with a comma separator).
On doing a POST, you can read this variable and only those fields present in this have been selected/filled in the form.
Hope this helps.
Try this.....
<?php
function checkvalue($val) {
if($val != "") return true;
else return false;
}
if(isset($_POST['submit'])) {
$values = array_filter(($_POST), "checkvalue");
$set_values = array_keys($values);
}
?>
In this manner you can get all the values that has been set in an array..
I'm not exactly sure to understand your intention. I assume that you have multiple form fields you'd like to part into different Web pages (e.g. a typical survey form).
If this is the case use sessions to store the different data of your forms until the "final submit button" (e.g. on the last page) has been pressed.
How do I know which ones are selected when i post the data from page 1 to page 2?
is a different question from how to avoid a large POST to PHP.
Assuming this is a table of data...
Just update everything regardless (if you've got the primary / unique keys set correctly)
Use Ajax to update individual rows as they are changed at the front end
Use Javascript to set a flag within each row when the data in that row is modified
Or store a representation of the existing data for each row as a hidden field for the row, on submission e.g.
print "<form....><table>\n";
foreach ($row as $id=>$r) {
print "<tr><td><input type='hidden' name='prev[$id]' value='"
. md5(serialize($r)) . "'>...
}
...at the receiving end...
foreach ($_POST['prev'] as $id=>$prev) {
$sent_back=array( /* the field values in the row */ );
if (md5(serialize($sent_back)) != $prev) {
// data has changed
update_record($id, $sent_back);
}
}

Get all variables sent with POST?

I need to insert all variables sent with post, they were checkboxes each representing a user.
If I use GET I get something like this:
?19=on&25=on&30=on
I need to insert the variables in the database.
How do I get all variables sent with POST? As an array or values separated with comas or something?
The variable $_POST is automatically populated.
Try var_dump($_POST); to see the contents.
You can access individual values like this: echo $_POST["name"];
This, of course, assumes your form is using the typical form encoding (i.e. enctype=”multipart/form-data”
If your post data is in another format (e.g. JSON or XML, you can do something like this:
$post = file_get_contents('php://input');
and $post will contain the raw data.
Assuming you're using the standard $_POST variable, you can test if a checkbox is checked like this:
if(isset($_POST['myCheckbox']) && $_POST['myCheckbox'] == 'Yes')
{
...
}
If you have an array of checkboxes (e.g.
<form action="myscript.php" method="post">
<input type="checkbox" name="myCheckbox[]" value="A" />val1<br />
<input type="checkbox" name="myCheckbox[]" value="B" />val2<br />
<input type="checkbox" name="myCheckbox[]" value="C" />val3<br />
<input type="checkbox" name="myCheckbox[]" value="D" />val4<br />
<input type="checkbox" name="myCheckbox[]" value="E" />val5
<input type="submit" name="Submit" value="Submit" />
</form>
Using [ ] in the checkbox name indicates that the selected values will be accessed by PHP script as an array. In this case $_POST['myCheckbox'] won't return a single string but will return an array consisting of all the values of the checkboxes that were checked.
For instance, if I checked all the boxes, $_POST['myCheckbox'] would be an array consisting of: {A, B, C, D, E}. Here's an example of how to retrieve the array of values and display them:
$myboxes = $_POST['myCheckbox'];
if(empty($myboxes))
{
echo("You didn't select any boxes.");
}
else
{
$i = count($myboxes);
echo("You selected $i box(es): <br>");
for($j = 0; $j < $i; $j++)
{
echo $myboxes[$j] . "<br>";
}
}
you should be able to access them from $_POST variable:
foreach ($_POST as $param_name => $param_val) {
echo "Param: $param_name; Value: $param_val<br />\n";
}
It is deprecated and not wished to access superglobals directly (since php 5.5 i think?)
Every modern IDE will tell you:
Do not Access Superglobals directly. Use some filter functions (e.g. filter_input)
For our solution, to get all request parameter, we have to use the method filter_input_array
To get all params from a input method use this:
$myGetArgs = filter_input_array(INPUT_GET);
$myPostArgs = filter_input_array(INPUT_POST);
$myServerArgs = filter_input_array(INPUT_SERVER);
$myCookieArgs = filter_input_array(INPUT_COOKIE);
...
Now you can use it in var_dump or your foreach-Loops
What not works is to access the $_REQUEST Superglobal with this method. It Allways returns NULL and that is correct.
If you need to get all Input params, comming over different methods, just merge them like in the following method:
function askForPostAndGetParams(){
return array_merge (
filter_input_array(INPUT_POST),
filter_input_array(INPUT_GET)
);
}
Edit: extended Version of this method (works also when one of the request methods are not set):
function askForRequestedArguments(){
$getArray = ($tmp = filter_input_array(INPUT_GET)) ? $tmp : Array();
$postArray = ($tmp = filter_input_array(INPUT_POST)) ? $tmp : Array();
$allRequests = array_merge($getArray, $postArray);
return $allRequests;
}
So, something like the $_POST array?
You can use http_build_query($_POST) to get them in a var=xxx&var2=yyy string again. Or just print_r($_POST) to see what's there.
Why not this, it's easy:
extract($_POST);
Using this u can get all post variable
print_r($_POST)

PHP multiple radio buttons

how can i process all radio buttons from the page?
<input type="radio" name="radio_1" value="some" />
<input type="radio" name="radio_1" value="some other" />
<input type="radio" name="radio_2" value="some" />
<input type="radio" name="radio_2" value="some other" />
this buttons will be added dynamically so i will not know the radio buttons name(and also the number of the buttons). Is there a way to get all radio values, with a for loop or something like this? thanks
Use a foreach loop
<?php
foreach ( $_POST as $key => $val )
echo "$key -> $val\n";
?>
$key will be the name of the selected option and $val, well, the value.
Since the browser will just change all your input to HTTP-formatted form data, you won't be able to tell what data is from a radio button versus a text box or other input.
If the naming convention is the same as your example, just loop until you don't find a value:
<?
for ($idx = 1; $idx <= 1000; $idx++) {
if (isset($_REQUEST["radio_$idx"])) {
// handle value
}
}
?>
EDIT Alternatively, if your form is generated dynamically, you could write the number of radio buttons it created as a hidden field in the form.
If you are able to alter the form that is being generated, you could write a hidden input that provided a list of all the radio buttons that you want to look for. As you are writing the radio buttons, just make a semi-colon-separated list of all the names that you make. When you are done, write that to a hidden input. Something like this:
On the source form:
<input type="hidden" name="radio_button_list" value="some_value;other_value" />
Then in your handler:
<?
$list = explode(';', $_REQUEST['radio_button_list']);
foreach ($list as $name) {
$value = $_REQUEST[$name];
// handle name & value
}
?>
jheddings' example says it all. However, you will never get the names / values of all buttons - just the selected one from each group. If you need literally all values, you will have to use Javascript.

How to retrieve information from Check Box?

My problem is a little bit complicate. (I use PHP)
I have two arrays, (simple arrays array[0] = string, array[1] = string...)
OK, now I will display the content of two arrays in a webpage.
The first array contain names and the second images URL.
Images and names are already displayed (my problem isn't here).
But now I want to do something else, add a check box near every image, those checkbox r active by default. Ok, now the user can uncheck some inbox;
The final aim, is to get a new array containing only the values of the names and images that had been checked.
I have thought of something simple, crawl the keys (number) of unchecked checkboxes and unset them from my array. But the problem that I didn't know how to deal with the check boxes
To receive inputs as arrays in PHP, you have to set their name using brackets in HTML:
<label><input type="checkbox" name="thename[]" value="" /> The text</label>
Then, when you access $_REQUEST['thename'] you'll get an array. Inspect it to see its format and play with it :)
first of all i recomend having just one array:
$array = array (0 => array('name' => '....', 'url' => '....'))
i think this will make your life much easier.
Also in the HTML you could also send the array key
foreach ($yourArray as $key=>$value) {
...
<INPUT type="checkbox" name="chkArr[<?php echo $key ?>]" value="1" checked/>
then in your form action you itarate the intial array and remove the unchecked ones.
foreach ($yourArray as $key=>$value) {
if (!isset($_POST['chkArr'][$key]) OR $_POST['chkArr'][$key]!='1') {
unset($yourArray[$key]);
}
}
<INPUT type="checkbox" name="chkArr[]" value="$num" checked/>
After the form is submitted, you'll have array $_REQUEST['chkArr'], in which you'll have numbers of the checkbox that are still checked.
To see which have been unchecked use array_diff($listOfAllNums, $chkArr)

Categories