PHP get checkbox value's separated by comma's - php

I have a contact form with a couple of checkboxes.
Whenever i submit the form I would like the selected value's to be printed separated by comma's.
<form method="POST">
<input type="checkbox" id="product1" name="product1" value="12">
<input type="checkbox" id="product2" name="product1" value="13">
<input type="checkbox" id="product3" name="product1" value="14">
<button type="submit">Subscribe</button>
</form>
I'm using this form. Lets say product 1 and 2 are selected. Then it should print 12,13 <
What is the best way to do this? Is it even possible?
Thanks in advance.
USE CASE:
So I thought it was useful to post why I need this.
Later when I'm able to get the values I will do something like this:
header("Location: http://test.com/$myvalues");
So this link can be test.com/12,13 after the user submits the form.
Not working:
So im using this code
<?php
if(isset($_POST['product'])){
$values = implode(',',$_POST['product']);
// header("Location: https://test.com/?add-to-cart=$values");
}
?>
Whenever i click on the submit button, it takes me to a page that doesnt exist. So i get a 404 page. Even with the header location commented off.
The header location doesnt seem to work at all.

<form method="POST" action="upload.php" >
<input type="checkbox" id="product1" name="product[]" value="12">
<input type="checkbox" id="product2" name="product[]" value="13">
<input type="checkbox" id="product3" name="product[]" value="14">
<button type="submit" name="products" >Subscribe</button>
</form>
in upload.php
$a=$_POST['product'];
$prodt=implode(',',$a);
$prodt has the value

To consolidate Alive to Die's answer and the comments about XSS by hanshenrik;
Use the array-like syntax in the input name attribute:
<form method="POST">
<input type="checkbox" id="product1" name="product[]" value="12">
<input type="checkbox" id="product2" name="product[]" value="13">
<input type="checkbox" id="product3" name="product[]" value="14">
<button type="submit">Subscribe</button>
</form>
If you check the first two checkboxes and submit, you should receive:
$POST['product'] == ["12", "13"];
Of course any input needs to be validated and escaped before outputting in the response. For the specific use-case you mention, you would end up with something like this:
$products = [];
if (isset($POST['product'])) {
foreach ($POST['product'] as $product) {
if (!is_numeric($product)) {
die("invalid product value.");
}
$products[] = intval($product);
}
}
if (empty($products)) {
die("no products selected.");
}
header("Location: https://test.com/" . implode(",", $products);
Clarification on input validation:
If you skip the input validation, one could submit the following data:
product[]="admin.php" and get redirected to https://test.com/admin.php. Of course that wasn't what you wanted this script to do, so by that principle alone you should consider restricting the possible behavior of your code. But it could get worse:
If you choose to echo implode(",", $POST['product']) somewhere in your website, someone might submit:
product[]="<script>alert(\"vuln\");</script>" which will add JavaScript to your website. An alert isn't dangerous, but this script could be anything. From submitting your session cookies to running a cryptominer in your browser. In principle, if you can alert(), you can do anything.
If you construct your original form from a database, someone might insert malicious inputs as values into the database. So these attacks are not necessarily limited to a single user playing around with their element inspector.
These are a lot of 'ifs' and for a simple local website or PHP script, you don't need to concern yourself with most of these issues. However, if you choose to make any of your code available to the internet, you should never trust user input.

Since you've given every checkbox the same name attribute, you can't. Give them separate names and you can easily handle this client and/or server side.

Related

Is it possible to use placeholders on <input type="submit">?

I'm currently working on at the displaying of information from a database. I was making a summary site where you can only see the important things of a table. After that i made the first element as an <input type="submit"> in a <form>, so u can click it and come to the detail site. My problem is now: The value of this input type has to be my ID, so i can query correctly on me detail site. I was wondering if it is possible to use something like a placeholder, so that the ID is the value, but on the input type is written other text.
My input:
<form method="post" action="Details.php">
<input type="submit" placeholder = "test" name="Overview" onclick="parent.location='Details.php'" value="<?php echo $data[$i1]; ?>">
</form>
How it currently looks
I want it that the input type still has the same value, but is displaying on the website something else like "test".
Greetings!
No, but buttons can have different values and labels.
<button name="foo" value="bar">baz</button>
Since you are using a form-tag per row, you can add a hidden input-field in the form and set the value of the submit-button to whatever you like.
<form method="post" action="Details.php">
<input type="hidden" name="id" value="<?php echo $data[$i1]; ?>" />
<input type="submit" name="Overview" value="test" />
</form>

proper structure for array of form field names for both jquery validation and php processing

The simplified form in the html code below contains a number of repetitive form fields which must be both validated by means of some jquery validate code and processed by means of some php code...I have set up the form field below to facilitate the php processing, but then again get stuck with writing the proper jquery validate code as the 'name' tags are supposed to be unique. If I'd make the name tags unique I think the php coding becomes more complex.
Just wondering what a proper structure of repetitive form fields would be which facilitates both the jquery validation coding and php coding?
Any suggestions?
Thank you in advance.
html code:
<input type="checkbox" id="check0" name="productselection[]" value="productselected0">
<input id="nrofparts0" type="text" name="nrofparts[]">
<input type="checkbox" id="check1" name="productselection[]" value="productselected1">
<input id="nrofparts1" type="text" name="nrofparts[]">
<input type="checkbox" id="check2" name="productselection[]" value="productselected2">
<input id="nrofparts2" type="text" name="nrofparts[]">
heres one way you can do it:
HTML
<form id="theForm" method="post">
<input type="checkbox" name="checky[0]" />
<input type="checkbox" name="checky[1]" />
<input type="checkbox" name="checky[2]" />
<input type="submit" name="submit" value="submit"/>
</form>
I add a key to the array because it makes it easier to determine which checkboxes were clicked. you wont get anything for an unclicked one. that can make it confusing
jquery:
$('#theForm input[type="checkbox"]').each(function(){
// if($(this))... some validation
});
php:
if(isset($_POST['checky'])){
foreach($_POST['checky'] as $key => $val){
echo $key.' '.$val; // this will give you the key of the checkbox, and the value
}
}
you could also have a hidden input that counts the checkboxes. That way when you loop, you can use it to set the empty checkboxes in your php code.
hope this helps!

Access form input in the same form

I am taking input from user in a form. Can I get that value(user input) to calculate other fields in the same form.
<input size="12" id="inputField" name="inputField" autofocus="" type="date" onblur="return dateValidate(this)"/>
Can I collect this form input later in the form and use it to calculate other fields. I was trying to using to use $_POST to retrieve the value but I am not sure if thuis is the right thing.
You cannot do it in PHP before submitting the form. You can easily do so in JavaScript. However you could simply add some AJAX code to send the value to your PHP script when user enters something in the box, and parse the response accordingly. PHP works on server side, and does not interact with user without any server side request
You can certainly do it in 2 ways...
1st way
<?php
$first_digit = '';
$second_digit = '';
$third_digit = '';
if(isset($_POST['calculate'])) {
$first_digit = $_POST['first_digit'];
$second_digit = $_POST['second_digit'];
$third_digit = $first_digit + $second_digit;
}
?>
<form method="POST">
<input type="text" name="first_digit" value="<?php if(isset($first_digit)) echo $first_digit; ?>" />
<input type="text" name="second_digit" value="<?php if(isset($second_digit)) echo $second_digit; ?>" />
<input type="text" name="third_digit" readonly value="<?php if(isset($third_digit)) echo $third_digit; ?>" />
<input type="submit" name="calculate" value="Calculate" />
</form>
2nd Way
Total the variables in the code and instead of showing the result output in a text box you can instead calculate and echo out the result, or you can store that in the database.
Note: Be sure you keep the third input[type=text] as readonly as it is showing you the calculated value so probably you don't want your users to change
Yes you can get input from user to calculate other fields in the same form, you should use scripts like OnChange() or onClick() to have this.

mysql_query result available on second post?

I am using a dynamically generated query string to display results from a search form for some reports - there are 5 search fields and $query2 could contain nothing or 5 additional search values.
$query="SELECT * from employee_work where company_id='$company_id' $query2";
When I POST the form I get the data displayed on screen which is great. I also then am using TCPDF to offer a PDF download of the data. I currently also the class for TCPDF via POST:
if($_POST['PDF']) {
do the TCPDF stuff......
}
<div id="export-buttons">
<form name="export" method="post" action="">
<input type="submit" name="PDF" value="PDF" class="button pdf">
</div>
The problem is that when a user clicks on the PDF button the POST array now only contains the value for the submit button and NOT the $query2 data from earlier so when I use TCPDF it outputs all the data and ignores the $query2 part of the search string.
How can I address this so either the original $query2 data stays available OR have anther way of checking if the form button has been clicked without overwriting the contents of POST? Can I use javascript to do this?
Thanks
Jason
why dont you add hidden inputs that have the values of the criteria from the search? That way when the user posts the request for the PDF you get also those fiels and can use them (AFTER making sure the values are SAFE) in the query.
Other safer way is to store in the session an object or array with the parameters that made the list and then pass the identifier of that search as a hidden input to the PDF form, like:
$_SESSION['sc0000001'] = array('field1'=>'value1', 'field2'=>'value2', 'field3'=123);
...
<form>
<input type="hidden" name="sc" value="0000001" />
...
</form>
when you post the form you get the identifier of the search and create the query with the criteria assign to session...
EDITED:
html before posting list criteria:
<form>
<input type="text" name="filter1" value="" />
<input type="text" name="filter2" value="" />
<input type="text" name="filter3" value="" />
<input type="text" name="filter4" value="" />
<input type="text" name="filter5" value="" />
...
<input type="submit" value="go go go" />
</form>
PHP that gets the filters, builds query, gets results and stores in session.
$sql = " select * from table_name where 1 ";
$arrFilters = array();
for($i=1;isset($_POST['filter'.$i]) && trim($_POST['filter'.$i])!="";$i++) {
$arrFilters['filter'.$i] = mysql_real_escape_string($_POST['filter'.$i]);
$sql.=" AND filter".$i."=".$arrFilters['filter'.$i];
}
// here you should have the complete $sql with the filters supplied
// lets save this search, we are going to keep only the last search from this user in his session.
$_SESSION['listingFilters'] = $arrFilters;
HTML with search results and after the form to get pdf:
<form>
<input type="submit" value="get pdf" />
</form>
PHP:
After the post to get the pdf we go check if there are filters
$sql = " select * from table_name where 1 "; // basic query
// get the filters array from session
$arrFilters = isset($_SESSION['listingFilters']) ? $_SESSION['listingFilters'] : array();
foreach($arrFilters as $filter => $value) { // for each filter add it to the query
$sql.=" AND filter".$i."=".$arrFilters['filter'.$i];
}
// here you should have the complete $sql with the filters in session
// and can do your pdf magic
Add pepper and salt to your pleasure (you need to revise the code to work for you and maybe also the query if you are using text has filters)
Without seeing more code, this is probably because you have two "forms" on the HTML page, with one submit button in one form, and another in the other form.
<form>
<input name="1" />
<input type="submit" name="go"/>
</form>
<form>
<input type="submit" name="createPDF" />
</form>
Make sure you have all the fields/buttons inside the one form.
<form>
<input name="1" />
<input type="submit" name="go"/>
<input type="submit" name="createPDF" />
</form>

submitted forms with the same name to a php script?

Is it possible to submit forms with input checkboxes, each containing the same name, to a PHP script?
Is it possible to loop through the names to get all the values?
I am building a message system, and users can add/remove recipients dynamically. When they do, a hidden checkbox is generated in the form containing the value, yet I'm not sure what to do with the name. On the php end, on top of the recipients a subject and a message are submitted, and the script needs to loop through each name and perform various SQL tasks. I know there are much better ways of doing this, and feel free to suggest, but I'd really like to know if it can get done this way. Comment if you need to see code, but I warn you, it's really confusing.
<input type="checkbox" name="samename[]">
// on the post/get:
foreach( $_POST['samename'] as $eachId ){
// do whatever you want. build the where in a query, ' set = '.$eachId
}
Yes you can, use the same name with [] after it, it will cause all of the values to be stored in an array on PHP.
<input type=checkbox value=1 name=check[]>
<input type=checkbox value=2 name=check[]>
<input type=checkbox value=3 name=check[]>
<input type=checkbox value=4 name=check[]>
<input type=checkbox value=5 name=check[]>
Yes you can, array of post, look at this example:
<?php
print_r($_POST);
?>
<form action="form.php" method="POST">
<input type="checkbox" name="vehicle[]" value="Bike" /> I have a bike<br />
<input type="checkbox" name="vehicle[]" value="Car" /> I have a car
<input type="submit" value="Submit" />
</form>
Notice how vehicle has the square brackets?

Categories