I'm new to PHP and having a problem reading checkboxes submitted by a form. Before explaining it i would like to mention that i'm trying to edit a much larger application and the data cannot be sent in any other way. It's just a matter of finding a good method of reading what is being sent.
When a normal text input is sent, the form will post the following:
custom[0][type]="text"
custom[0][name]="VariableName"
custom[0][value]="VariableName"
Basically there is a main "custom" multidimensional array that has several elements (0,1,2,3 etc) and each element has name and value.
However, when one of the elements is a checkbox, the following stuff gets posted:
custom[1][type]="list"
custom[1][name]="SelectedOptions"
custom[1][value]="Value1"
custom[1][value]="Value3"
custom[1][value]="Value5"
Getting to the PHP side of things, this is the code i'm using to read the data sent by the form. The code below works ok in scenario 1 (with text based inputs) but only reads one value when we have list type custom data.
foreach($_POST['custom'] as $item){
if($item['value'] != "") echo $item['name'].'='.$item['value']
}
The problem is that $item['value'] only reads one of the values, not all 3. How can i get all 3 values in a variable ? It probably is a very easy thing...
To put it all combined, this is what it is sent with POST (3 checkboxes are checked for Variable2)
custom[0][name] Variable1
custom[0][type] text
custom[0][value] ValueForVariable1
custom[1][name] Variable2
custom[1][type] checkbox
custom[1][value] Value1
custom[1][value] Value3
custom[1][value] Value5
And this is what print_r($_POST) shows for the posted data above
[custom] => Array
(
[0] => Array
(
[value] => ValueForVariable1
[name] => Variable1
[type] => text
)
[1] => Array
(
[value] => Value1
[name] => Variable2
[type] => checkbox
)
Just to be sure we're all on the same page, the actual data is generated by a more complex system and we can't really change that. I'm interested in seeing how we can read all 3 values for Variable2 that are sent in the POST.
Thanks !
EDIT:
With the extra information that you've since provided, I see that I originally misunderstood the problem.
Since you have no control over over the form that sends the data to your PHP script, and thus can't change it to ensure that the later checkboxes with the same name do not overwrite the earlier ones, you'll have to get access to and process the raw post data itself.
$postdata = file_get_contents("php://input");
echo $postdata;
... will output the postdata just like a GET querystring: blah=1&blah=2&blah=3 (blah indicates 3 form fields with the same name blah, the first two of which would be overwritten in $_POST leaving $_POST['blah'] = 3).
with a little exploding on & and looping and parsing looking for the variables in question, or even any conflicting variables, will get you where you're trying to go.
Original Answer:
HTML forms only submit checkboxes (or radio buttons) that have been checked. If they haven't been checked, the browser won't send the data back to the server.
The main way to solve this is to know what you're looking for on the back end and test for it (i.e. if (isset($_POST['checkboxname'])).
If you truly need a general purpose backend that will dynamically incorporate all checkbox elements, checked or not, the way I've solved this in the past is to use javascript to record all form elements on the page and submit that info with the rest of the form (and, in my case, also submit whether that field was changed or not).
Here's a function that you can run at the top of the script to treat POST the way you expect it to be treated from your ASP background:
function post_process() {
$rawpostdata = file_get_contents('php://input');
if (!$rawpostdata) return;
$fields = explode('&', $rawpostdata);
$post = array();
foreach ($fields as $field) {
list($key, $val) = explode('=', $field);
if (isset($post[$key])) $post[$key] .= ','.$val;
else $post[$key] = $val;
}
$_POST = $post;
}
Related
Im using wordpress with the activecampaign plugin. Im trying to use a webhook to send a contacts email data to a php page where i can do something with this information. How do i receive data structured as following in php:
Encoded
contact%5Bid%5D=67330&contact%5Bemail%5D=asdf%40d.nl&contact%5Bfirst_name%5D=sadf&contact%5Blast_name%5D=asdf&contact%5Bphone%5D=%2B1063494959&contact%5Borgname%5D=&contact%5Bcustomer_acct_name%5D=&contact%5Btags%5D=&contact%5Bip4%5D=0.0.0.0&seriesid=266
Decoded
contact[id]=67330&contact[email]=asdf#d.nl&contact[first_name]=sadf&contact[last_name]=asdf&contact[phone]=+1624567935&contact[orgname]=&contact[customer_acct_name]=&contact[tags]=&contact[ip4]=0.0.0.0&seriesid=266
I tried using $email = $_POST["contact[email]"]; but no luck.
Here is the thing whenever you use a bracket as identifier for a data to be sent in POST it's going to form the associative array like $key=>$value relation in your case for example if contact[email] has been received through post request it will be like associative array of a form $contact=>$email which can be accessed in this case by using $_POST['contact']['email'] because the data will take the following array structure Array ( [contact] => Array ( [email] => someone#somewhere.com ) )
to sum up things your above request will work if you just copied the following
$email=$_POST['contact']['email'];
If the answer worked don't forget to accept and up vote so that other could benefit and easily spot the right answer. if you faced further problem don't hesitate to ask in comment. peace ;-)
You could use explode with urldecode functions:
Look at the example:
$query = "my=apples&are=green+and+red";
foreach (explode('&', $query) as $chunk) {
$param = explode("=", $chunk);
if ($param) {
printf("Param\"%s\" - \"%s\"<br/>\n", urldecode($param[0]), urldecode($param[1]));
}
}
TL;DR version
I have a big form with hundreds of html input elements on it, I made a php array to store all the element names in it. When I run my process.php file it runs through that array using a loop and creates a new array, the key of that array is the name of each element, and the value of that array is the value of each element. I know this code works as element values for text boxes, radio buttons, and drop-down selections work fine. Checkboxes do not have the values put into the array, instead the key and value read the same thing, the name of the element. Why is $_POST giving me the NAME or ID of my checkbox, and not its value?
Full explanation /w code samples:
The problem I am having seems rather unusual to me as from my understanding it goes against how $_POST should work.
In any case I have been developing a travel insurance website for the past year and it is nearing completion. The client wants me to create a version of the form which they can view after people have submitted applications and it will get the values out of the file they select.
My problem is that $_POST is not getting the value of my checkbox elements but rather their name or id (both are identical so I cannot be sure which it is getting). $_POST is successfully getting the value of all radio, text, and drop-down elements, just not checkboxes.
I have a very large array in my process.php file as the form is quite large. What I've done is create an array which has the name of each element I wish to access. Below is a sample of the structure the array follows, it is far to large to post the entire thing here (400 plus elements on form).
$form_data = array
('trav_emer_med_insur',
'trav_emer_single',
'trav_emer_single_date_go',
'trav_emer_single_date_ba',
'trav_emer_single_days',
'trav_emer_annual',
'trav_emer_annual_date_go',
'trav_emer_annual_days',
'trav_emer_extend',
'trav_emer_extend_date_go',
'trav_emer_extend_date_ef',
'trav_emer_extend_date_ba',
'trav_emer_extend_days',
);
This is the code that runs on process.php to create the user data file, which is saved to a protected folder on the server.
// Create user output data
$out_data = array();
$count = count($form_data);
for( $i = 0; $i < $count; $i++ )
{
if(empty($_POST[$form_data[$i]])) {
$out_data[$form_data[$i]] = " ";
}
else {
$out_data[$form_data[$i]] = $_POST[$form_data[$i]];
}
}
//Set variable names for new file
$dir = "/home/imelnick/public_html/getawayinsured.ca/userdata/";
$timestamp=date("YmdGis");
$name = $out_data['txtApp1Name'];
$value = str_replace(" ", "", $name);
$item = $value . "^" . $timestamp . ".txt";
$filename = $dir . $item;
//Put data in file
//Open file for writing
$fileHandle = fopen($filename, 'w') or die("Can't open file");
//Write contents of out_data array to file
foreach ($out_data as $key => $value) {
$fileLine = $key . "\t" . $value . "\r\n";
fwrite($fileHandle, $fileLine);
}
//Close file
fclose($fileHandle);
The first block of names in the array belong to checkboxes and they follow the format of the following:
<input type="checkbox" name="trav_emer_med_insur" id="trav_emer_med_insur_if" value="YES" class="form_elements" onClick="if(this.checked){document.getElementById('trav_emer_med_options').style.display='block';}else{document.getElementById('trav_emer_med_options').style.display='none';}"/>
The onClick statement expands a div containing additional checkboxes which offer further options to the applicant.
My output data array which is created from the form data has the key of each item in the array as the name of the element, and the value of each item in the array the value of the corresponding HTML element.
Upon splitting the array and writing the $key/$value combination the expected value of $_POST[$form_data[0]] (note: $form_data[0] = trav_emer_med_insur) is the value of the above checkbox code, value="YES". However the output in the file reads as follows.
trav_emer_med_insur trav_emer_med_insur
I am quite sure that there is not a problem with the code that processes the form itself as other elements on the form have their values saved perfectly well to the file (radio buttons, text boxes, drop-downs all work). The Checkboxes do not, they refuse to $_POST the value of the HTML element, and simply keep putting out the name twice.
For example, another element in the form not listed in my array sample above named smoked_if is a radio button pair which asks if the applicant has smoked or not. Here is a sample output from a recent application.
As can be seen the desired result of my code is being performed.
smoked_if no
I am at a loss here because not only does this contradict the functionality of $_POST itself but since all other elements on the form have their values posted without issue it tells me there is a problem with checkbox elements and $_POST.
Any assistance is greatly appreciated.
I think your problem might be related to the fact that checkboxes are not posted when they are not checked.
See Post the checkboxes that are unchecked
if you need to get around this behaviour
AS long as the information is inside of the Form tags, it will be passed to the server. With that said, you need to understand that what is sent to the server is the NAME and VALUE of the items.
When you are looking at PHP, you want to submit, and then a string will look like: sample from http://www.w3schools.com/tags/tryit.asp?filename=tryhtml_form_checkbox as well
?vehicle=car&vehicle=truck
In PHP when you post it, the idea is the same but just hidden from the unskilled eyes. To get the values of it in my example:
$vehicle= $_POST["vehicle"];
echo ''.$vehicle; //shows ARRAY
foreach( $item in $vehicle){
echo ''.$item.'\n'; //will iterate through all the vehicle and print them out
}
YOu can also say things like
if(in_array("car", $vehicle)){
echo "there exists a car\n";
}
http://php.net/manual/en/function.in-array.php
Since the checkboxes are posted only if they are checked, you need a workaround for that. I think the most usual fix is to use a hidden input with the same name as the checkbox's and usually 0 as value. And do not forget to put the hidden input before the checkbox :)
This way even if the checkbox is not checked you get the value of the hidden input. If the checkbox is selected the hidden field's value is overwritten in the POST array by the one from the checkbox.
I have some checkboxes in my app, which could be checked (naturally). This checkboxes are named like 'checkboxname[]', and every checkbox has it's own value (4,5,6,7,8, and so on).
Now I would like to get all the values (just from the checked checkboxes!!) into an array, send this array over ft.upload, and split the array with foreach with php. But my php file is always saying that the arguments are invalid for my foreach function.
Heres the javascript.
var values = new Array();
$("input[name='checkboxname[]']:checked").each(function(){values.push($(this).val());});
params.checkboxname = values;
Heres the php code.
$rubriks = $_POST['checkboxname'];
foreach($rubriks as $ausgabe){
echo $ausgabe; }
I don't know whats wrong. I tested with var_dump whats actually send from the javascript, an theres no checkbox-array so I think there is the problem?!
I have made an interface whereby the user can create his own form. I've just managed to load that form in a separate php file.
What I want to know is that after posting the form, how do I capture all the id and values of the inputs in an array so that I can display the the form (read-only) and display it on another page.
If your <form> method attribute is post - you send POST request to server. You can access all POST data through $_POST like var_dump($_POST);.
If your <form> method attribute is get or you have no method set - you send GET request to server. You can access all GET data through $_GET like var_dump($_GET);.
No matter which input fields was in form - they all would be here.
$post = array();
foreach($_POST as $key => $value) {
$post[$key] => $value;
}
But this example is not too good. It's not protected against SQL-injection - pay attention to it. But with it you can get all $_POST data in $post array.
When you post a form, you have the "array" $_GET or $_POST according to the method (but you could use $_REQUEST which gets both post and get "arguments") where you have all the data you need to process the content of the form. The PHP array_keys returns the keys which are the names given for each field in the form. Using each key in a loop, you can do some kind of processing over the "content" of that field, that you can retrieve using the current key in the loop; e.g.
foreach(array_keys($_GET) as $a)
{
echo $a . " => " . $_GET[$a];
}
I have a survey script that has 3 questions per page. When users answer the questions on the first page and click next, the data from the previous page is stored in $_SESSION['survey']['data'] by doing this:
$data = postToArray($_POST, $ignore_fields);
$_SESSION['survey']['data'] = $data;
$data is an array that looks like:
array('question' => 'answer', 'question' => 'answer');
postToArray does a few checks and manipulates the actual submission a bit, before returning it to $data.
When the user is on page two of the survey, the same thing happens over. I assumed that when $data gets added to the session, via $_SESSION['survey']['data'] = $data;, that it would append to the session array if the 'question' (key) did not exist, but if it did (because the user went to a previous page and changed their answer), that the existing value with the same key would be overwritten, however the last page's submission overwrites everything in the ['data'] array in the session. Come to think about it, that makes perfectly sense.
I tried various things, such as retrieving the $_SESSION['survey']['data'], storing it in array, reading the last submission, merging the arrays, and then re-saving everything in the SESSION, but my code didn't work out -- does this approach make sense? Is that possible?
I also tried array_push, but no luck there.
In addition, I tried adding to $_SESSION['survey']['data'][], which at least saves everything (each submission in its own array), but then if the user goes back a page, any values they change and re-submit are added as another array.
Preferably, I'd like one giant array with all questions/answers and it keeps adding to that array and overwrites any values with existing keys.
What's the best approach?
Thanks,
-Ryan
SOLUTION IMPLEMENTED
$data = postToArray($_POST, $ignore_fields);
foreach($data as $question => $answer)
{
$_SESSION['survey']['data'][$question] = $answer;
}
Try to serialize the data before saving it in a session variable.
http://php.net/manual/en/function.serialize.php
Loop through the $data array and set it up as naiquevin stated, $_SESSION['survey']['data'][$data['question']] = $data['answer'].
<?php
session_start();
if(!isset($_POST["submit"])){
$_SESSION["abc"]=array("C", "C++","JAVA","C#","PHP");
}
if(isset($_POST["submit"])){
$aa=$_POST['text1'];
array_push( $_SESSION["abc"],$aa);
echo "hello";
foreach( $_SESSION["abc"] as $key=>$val)
{
echo $val;
}
}
?>