HTML multiple checkboxes with identical name= into PHP $_POST - php

So I have a 3rd party survey tool that generates html surveys, and for multi-select checkboxes in a given question, it will name them all the same:
<input type="checkbox" value="1" id="V25_1" name="V25">
<input type="checkbox" value="2" id="V25_2" name="V25">
Is there a way that all the selected values can be retrieved in PHP?
$_POST by default seems to simply store only the last selected value.

Your code should be approximately the following:
<select multiple="multiple">
<input type="checkbox" value="1" id="V25_1" name="V25[]">
<input type="checkbox" value="2" id="V25_2" name="V25[]">
</select>
V25[] means that you can get the value from an array. e.g. $_GET['V25'][0]
You could also specify an index if needed:
V25[1] or V25[a]

You could run something like this before the form submit:
$(":checkbox").each(function(){
$(this).attr("name",$(this).attr("id"));
});
or
$(":checkbox").each(function(){
$(this).attr("name",$(this).attr("name")+"[]");
});

It is possible to retrieve all variables when you have multiple elements with identical 'name' parameters.
After much scouring the internet for a solution, I wrote the following php script which grabs the raw post data, and parses it:
<?php
function RawPostToArray() {
$rawPostData = file_get_contents("php://input");
if($rawPostData) {
$rawPostData = explode('&', $rawPostData);
if($rawPostData && is_array($rawPostData) && count($rawPostData)) {
$result = array();
foreach($rawPostData as $entry) {
$thisArray = array();
$split = explode('=', urldecode($entry), 2);
$value = (count($split) == 2) ? $split[1] : '';
if(array_key_exists($split[0], $result)) {
if(is_array($result[$split[0]])) {
$result[$split[0]][] = $value;
}
else {
$thisArray[] = $result[$split[0]];
$thisArray[] = $value;
$result[$split[0]] = $thisArray;
}
}
else {
$result[$split[0]] = $split[1];
}
}
return $result;
}
else return array();
}
else return array();
}
?>
Any duplicate 'names' are bumped down into an array within the result, much the way $_POST does, when the HTML is coded correctly.
There is probably plenty of room for improvement here, and I'm sure not all situations are accounted for, but it works well for my application.
Suggestions are appreciated where improvements can be made.

Related

Sum Selected Checkbox Values using PHP

I've been figuring out ways on how to work this out but I can't seem to. I'm a beginner in PHP and I'm so lost right now. I want to sum the selected checkboxes's values and post the sum of the values in a PHP page.
Here's my HTML so far
<input class="wrapped-input" type="checkbox" value="290" id="widgetu15650_input" name="custom_U15293[]" tabindex="1"/>
<label for="widgetu15650_input"></label>
Here's my PHP so far
if (isset($_POST['u15175'])) {
if($_POST){
$val = 0;
foreach($_POST['custom_U15293'] as $custom_U15293){
$val += $custom_U15293;
}
echo $val;
}
}
Try this,
if($_POST){
if(isset($_POST['custom_U15293']){
$val = 0;
foreach($_POST['custom_U15293'] as $custom_U15293){
$val += (int) $custom_U15293;
}
echo $val;
} else {
echo 'Value not received';
}
If you see Value not received there is some problem with your HTML code

Send radio selection to function along with textbox

I've got some code working that takes the text from my input box and moves it across to a function. I'm now trying to change it so I add another form element, a radio button and I want to access the choice within my functions.php file.
This is my current code which works for the post name, but what if I want to also grab the colours boxes that was selected too?
main.php
<?php
if (isset($_POST['submit'])) {
$data = $_POST['name']; // the data from the form input.
}
?>
...
<form action="/" method="post">
<input type="text" name="name" placeholder="Acme Corp"/>
<input name="colour" type="radio" value="red">Red<br>
<input name="colour" type="radio" value="blue">Blue<br>
<input name="colour" type="radio" value="green">Green<br>
<input type="submit" name="submit" value="Submit">
</form>
<img src="pngfile.php?data=<?php print urlencode($data);?>"
alt="png php file">
I guess I confused because currently it is calling this:
pngfile.php
<?php
require_once 'functions.php';
$inputData = urldecode($_GET['data']);
process($inputData);
exit;
?>
Which calls functions.php
<?php
function process($inputdata)
{
...
EDIT: What I have tried:
main.php [Change]
$data = $_POST['name'] && $_POST['colour']
But I'm not really sure how to progress.
Never trust user input. Sanitize and validate your inputs before using them.
This can be arranged better, but the basics are still true.
PHP Manual: filter_input_array()
PHP Manual: filter_var_array()
Small Function Library
function sanitizeArray($filterRules)
{
return filter_input_array(INPUT_POST, $filterRules, true)
}
function validateArray($filteredData, $validationRules)
{
return filter_var_array($filteredData, $validationRules, true);
}
function checkFilterResults(array $testArray, array &$errors)
{
if (!in_array(false, $testArray, true) || !in_array(null, $testArray, true)) {
foreach($testArray as $key => $value)
{
$errors[$key] = '';
}
return true;
}
if ($testArray['name'] !== true) { //You can make a function and do various test.
$errors['name'] = 'That is not a valid name.';
}
if ($testArray['clour'] !== true) { //You can make a function and do many test.
$errors['colour'] = 'That is not a valid colour.';
}
return false;
}
function processUserInput(array &$filteredData, array $filterRulesArray, array $validationRulesArray, array &$cleanData, array &$errors)
{
$filteredInput = null;
$tempData = sanitizeArray($filterRulesArray);
if (!$checkFilterResults($tempData, $errors)){
throw new UnexpectedValueException("An input value was unable to be sanitized.");
//Consider forcing the page to redraw.
}
$filteredData = $tempData;
$validatedData = validateArray($filteredData, $validationRulesArray);
if (!$checkFilterResults($validatedData, $errors)){
return false;
}
$errors['form'] = '';
$cleanData = $validatedData;
return true;
}
function htmlEscapeArray(array &$filteredData)
{
foreach($filteredData as $key => &$value)
{
$value = htmlspecialchars($value, ENT_QUOTES | ENT_HTML5, 'UTF-8', false);
}
return;
}
Basic Main Line
try {
$filterRulesArray = []; //You define this.
$filteredData = []; //A temporary array.
$validationRulesArray = []; //You define this.
$validatedData = null; //Another temporary array.
$results = null; //Input processing results: true or false.
$cleanData = null; //Filtered and validated input array.
$errors = []; //Any errors that have accumulated.
if (isset($_POST, $_POST['submit'], $_POST['colour']) && !empty($_POST)) {
$results = processUserInput($filteredData, $filterRulesArray, $validationRulesArray, $cleanData, $errors);
} else {
$errors['form'] = "You must fill out the form."
}
if ($results === true) {
$name = $cleanData['name']; //You can do what you want.
$colour = $cleanData['colour']; //You can do what you want.
//header("Location: http://url.com/registration/thankYou/")
//exit;
}
//Prepare user input for re-display in browser
htmlEscapeArray($filteredData);
} catch (Exception $e) {
header("Location: http://url.com/samePage/"); //Force a page reload.
}
Let the form redraw if input processing fails.
Use the $errors array to display error messages.
Use the $filteredData array to make the form sticky.
<html>
<head>
<title>Your Webpage</title>
</head>
<body>
<h1>My Form</h1>
<form action="/" method="post">
<!-- Make spots for error messages -->
<input type="text" name="name" placeholder="Acme Corp" value="PUT PHP HERE"/>
<!-- No time to display sticky radios! :-) -->
<input name="colour" type="radio" checked="checked" value="red">Red<br>
<input name="colour" type="radio" value="blue">Blue<br>
<input name="colour" type="radio" value="green">Green<br>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
Tip:
It may be better to submit numbers for radios, as opposed to longer string values like (red, green, blue). Numbers are easier to sanitize and validate. Naturally, then you must translate the input number into its corresponding string. You would do that after validation has finished, but before using the values. Good luck!
you can access this using array like this.
$data[] = $_POST['name'];
$data[] =$_POST['colour'];
Or combine both variable
$data = $_POST['name'].'&'.$_POST['colour'];
Use Array in php for this process as follows:
if (isset($_POST['submit'])) {
$array_val = array(
"name"=> $_POST['name'],
"color"=> $_POST['color']
);
}

Declare php variables by for loop in array

How to declare variables in the array using for loop. I have 3 input fields on my page, so when the submit buttons is pressed, it should process the following line of code. On my html page, there are fields named: question1, question2, and question3.
Here's the code of process.php file. It doesn't work for some reason, I suppose there are several mistakes here but I cannot find em.
<?php
$question = array();
for($j=1; $j<4; $j++) {
$question[j] = $_POST['question[j]'];
$result;
$n=1;
if($question[j] != "") {
$result = $n.'): '.$question[j].'<br/><br/>';
$n++;
}
}
echo $result;
?>
<?php
$question = array();
$result = "";
for($j=1; $j<4; j++) {
$question[$j] = $_POST["question$j"];
if($question[$j] != "") {
$result .= $j.'): '.htmlentities($question[$j]).'<br/><br/>';
}
}
echo $result;
?>
Though you don't need an array.
<?php
$result = "";
for($j=1; $j<4; j++) {
$result .= $_POST["question$j"]!="" ? htmlentities($_POST["question$j"]).'<br/><br/>':'';
}
echo $result;
?>
For starters, arrays are zero-indexed, so I think you want this:
for($j=0; $j<3; j++)
Aside form that, this doesn't evaluate the value of j:
$_POST['question[j]']
I think you might want something like this:
$_POST["question$j"]
However, if you made the indexing change above, since your elements are named starting with 1 instead of 0 then you'd need to account for that:
$_POST['question' . $j+1]
You can use following HTML code
<input type="text" name="question[a]" />
<input type="text" name="question[b]" />
<input type="text" name="question[c]" />
with following PHP code:
foreach($_POST["question"] as $key => $value)
{
// $key == "a", "b" or "c"
// $value == field values
}
Remember to sanitize Your input!

PHP/HTML : How to access checkboxes dynamically generated in loop

I have checkboxes which is generated in while loop. These checkboxes are always checked for the first time and the value stored in the database is "On". But when user unchecks it, I want to store "Off" in database. But my problem is i am not able to access the checkbox name to check if which checkboxes are unchecked on button click. I wrote this code
while($row = mysql_fetch_assoc($result)) {
if($pck_id_renew == 'On')
{
echo '<td class=c><input type="checkbox" id="renew_chk" name="renew_chk"
checked="checked" style="width:50px" value="On"/></td>';
}
if($pck_id_renew == 'Off') {
echo '<td class=c><input type="checkbox" id="renew_chk" name="renew_chk"
style="width:50px" value="Off"/></td>';
}
}
You will only receive the input value of checkboxes that are checked. Use an array and store all available checkbox names in it. Loop through this array to detect which checkboxes are checked/unchecked.
Code may look something like this:
// Define available checkboxes
$inputs = array('renew_chk', ...);
// Check input values
$values = array();
foreach ($inputs as $input) {
if (isset($_POST[$input])) {
$values[$input] = 'On';
}
else {
$values[$input] = 'Off';
}
}
// Loop through $values and store value in database
foreach ($values as $input => $value) {
// UPDATE database SET $input = $value WHERE id = [n];
}

Server Side Form Validation PHP with multi-file Upload

HTML:
Owner: input type="text" name="owner[]" />
Category:
<select name="cat[]">
<option value="clothes">Clothes</option>
<option value="shoes">Shoes</option>
<option value="accessories">Accessories</option>
</select>
Upload: <input type="file" name="image[]" />
whith function that clone the same fields when click on "+ button"
I count the POST field with:
$num = count($_FILES['image']['name']);
because i want to know how many times the end user clone the fields.
what i want is Make sure that the user has to fill all fields which he opend with "+ button" i cant check all the hidden fields i want to check just the field he opend.
so what can i do ?
i cant do like this:
$owner = $_POST['owner'][$i];
$cat = $_POST['cat'][$i];
$file = $_FILES['image'][$i];
if ($owner && $cat && $file)
echo "bla bla bla";
else
echo "fill all the fields!";
can anyone help me ?
thank you
There are some points which you need to make sure beforehand. Whenever you are using any input field's name attribute as "owner[]" or "cat[]" or "image[]", you will get an array then. But since, input file's property accessing capability is already 2D array by default, so now you will be able to access those properties as a 3D array.
When you have added a "[]" for the input file field's name attribute, you will now get the name of the 1st file as "$_FILES['image'][0]['name']", because array indices start with 0. As per your question, you can validate using the following way:-
<?php
$numOwners = count($_POST['owner']);
$numCats = count($_POST['cat']);
$numFiles = count($_FILES['image']);
// Check to see if the number of Fields for each (Owners, Categories & Files) are the same
if ($numFiles === $numCats && $numFiles === $numOwners) {
$boolInconsistencyOwners = FALSE;
$boolInconsistencyCats = FALSE;
$boolInconsistencyFiles = FALSE;
for ($i = 0; $i < $numFiles; $i++) {
if (empty($_POST['owner'][$i])) {
$boolInconsistencyOwners = TRUE;
break;
}
if (empty($_POST['cat'][$i])) {
$boolInconsistencyCats = TRUE;
break;
}
if (!is_uploaded_file($_FILES['image'][$i]['tmp_name'])) {
$boolInconsistencyFiles = TRUE;
break;
}
}
if ($boolInconsistencyOwners || $boolInconsistencyCats || $boolInconsistencyFiles) {
echo "I knew that there will be some problems with users' mentality!";
// Redirect with proper Error Messages
}
else {
echo "Wow, Users have improved & have become quite obedient!";
// Proceed with normal requirements
}
}
else {
echo "Something fishy is going on!";
}
?>
Hope it helps.

Categories