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];
}
Related
I have a web form that submits some hidden input fields with post parameters and I want to use Request object from Symfony.
This is how I'm doing it now using an API based request also with Postman app I can access the son values like this.
myAction(Request $request){
$content = $request->getContent();
$params = json_decode($content, true);
$value = $params['value'];
}
But when i use a web form it doesn't get the values this way. I was trying to figure out how to get the values and i ended up using the post variable which works fine.
$value = $_POST['value'];
I don't want to use the global variable but rather grab the value from the request. I don't have a super good reason why, other than I prefer it the Request way. Any help would be appreciated.
Is there something special I'd have to do with the HTML form?
Use $value = $request->request->get('value'); to get a single POST value.
Use $values = $request->request->all() to get all POST values.
From symfony docs
I have a form that has 3 steps. I use SESSIONS to keep values from step to step. When I open the same form in another tab and complete the first step, this immediately replaces the Session values from the other form.
So how can I create sessions with field values that are attached to a specific form? I need to avoid Session conflicts.
If the forms are indeed different, then put it in a multi-dimensional array:
$_SESSION['register']['field1']=$_POST['field1'];
$_SESSION['contact']['field1']=$_POST['field1'];
If it is the same form and it is just a new tab, you can either check if the value was set before and ignore it, set a flag to say there is a form submission in progress, or entirely delete the old session values so the new form in the new tab has no values attached.
I use this function to handle form input:
function Hold_Form_Input($formname)
{
$FormPost = array();
foreach ($_POST as $key => $entry)
{
$FormPost[$key]= $entry;
}
$_SESSION[$formname]= $FormPost;
}
And I pass the form name in with a hidden input.
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'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;
}
This may be asking a lot, but I am looking for a way to detect the attributes in some of my form input fields.
For example:
<input type="text" name="fieldone" id="fieldone" value="me#me.com" />
I can simply use a php foreach loop to get the key => value information.
<?php
$querystring = "";
if ($_POST){ $kv = array();
foreach ($_POST as $key => $value){ $querystring .= "$key=$value<br>"; }
}
?>
And this helps with mediocre debugging reasons.
However, this only detects the name and value of the form field. How do I detect the "id" attribute, or any custom attributes I may add.
Is there a way to detect/display the attributes of POST variables? Or does php stop at the name/value?
Only Name and value are senet to the server. ID and other attributes are not sent at all (why would they).
BTW: You'll want to use print_r($_POST); or var_dump($_POST); instead of your loop.
Nothing except the name and value are sent over HTTP.
You'll need to use some JavaScript pre-processing for that.
For example, on form submit, you could use JavaScript to store all the attributes with the name, but this will be messy.
When a form is submitted, only the name and value fields are used. The other fields are only used client side (inside the browser) and not returned to the server.