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.
Related
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 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 form in the footer of my website that appears on each page. I need to make it so if a user submits the form with blank fields, it will flag the error message in the form. It currently directs them to a different page where there data is submitted to another server. I'm already using JavaScript for this, but need to add an additional validation layer with server-side code.
I know how to detect if the form fields are empty, but how can I use server-side code to redirect back to the referring page and include some parameters that can be used in the footer to detect which fields were empty?
I'm assuming I'd have to use PHP's header() with the http_referer, but how can I pass the parameters back to that page without anything showing up in the URL?
Keep a record in $_SESSION of the invalid/empty fields and flag them with CSS in your form:
session_start();
// When you begin validating your form, clear out any old fields from $_SESSION
$_SESSION['previous'] = array();
$_SESSION['invalid'] = array();
// when you encounter an empty or invalid field,
// add it to an array in $_SESSION
$_SESSION['invalid']['fieldname'] = TRUE;
// Store the previous POST value too
$_SESSION['previous']['fieldname'] = $_POST['fieldname'];
In your form, you can check if there's an invalid field and add a CSS class to indicate invalidity. This sets the class invalid:
<input name='fieldname' type='text'
class='<?php if (isset($_SESSION['invalid']['fieldname'])) echo "invalid";?>'
value='<?php if (isset($_SESSION['previous']['fieldname'])) echo htmlentities($_SESSION['previous']['fieldname'], ENT_QUOTES); ?>'
/>
Do this for all your form fields. Use the same method to retain the previous $_POST values and echo them out into the field's value attribute.
I don't think there is a need to send them to another page. As you already know data validation is easy to do using Javascript, and PHP.
you should check the POSTed form data at the top of the file.
Validate the data. Put errors into an array so you can echo the errors at anytime.
Check to see if you found any errors.
// Loop through the $_POST array, which comes from the form...
$errors = array();
foreach($_POST AS $key => $value)
{
// first need to make sure this is an allowed field
if(in_array($key, $allowedFields))
{
$$key = $value;
// is this a required field?
if(in_array($key, $requiredFields) && $value == '')
{
$errors[] = "The field $key is required.";
}
}
}
If there are errors, redisplay the page and list the errors so the users know what they did wrong, and can fix them. This method also allows you to repopulate the form fields with saved values so if there is an error the user doesn't have to type everything in again.
Just wondering If there is a quick code/ short cut to get all textbox, combobox and radio button values in the current html page using php. Instead of $_Get and give names for each.
I have 4 pages in my application, where a user can go back and forth, I want to retain all values the user inputted in my page, some of the controls are static and rest are dynamically created. I just want a generic way of retaining all input boxes with values, instead of specifying names for each
You can enumerate them all using a foreach loop as such:
foreach($_GET as $name => $value) {
echo "<b>", $name, ":</b> ", $value;
}
I don't see the usefulness of doing that. Without field names, there is no way of distinguishing between multiple input areas. Maybe provide an example of exactly what you are trying to achieve?
If you're using GET to transfer form data, then you just need to make sure you pass all those parameters in the URL string to the next page. You could use foreach to construct the query string as such:
$returnStr = "";
foreach($_GET as $name => $value) {
if ($name = ((array_keys($_GET)[0]))
$returnStr .= sprintf("?%s=%s", $name, $value);
else
$returnStr .= sprintf("&%s=%s", $name, $value);
}
// now $returnStr is of the form "?key1=value1&key2=value2"...
Then, in your form that you are using to submit data, append $returnStr to the action attribute:
...
<form method="get" action="page2.php<?php echo $returnStr; ?>">
...
This should append any extra data fields you create to the get request. Keep in mind this would be harder to do with post... although post is a bit more secure since your values aren't just sitting in the URL bar.
I haven't actually tested this since I don't have a PHP-enable server here, but it should work..
The question is not very clear, however if you simply want to display all of the form field names and values, the easiest way is:
echo '<pre>' . print_r($_GET, 1) . '</pre>';
The print_r function is very useful when working with forms with a lot of fields.
Hey, I'm programming a feedback form on a website for a client, however, there are over 100 inputs (all uniquely named). I was wondering if there was a loop I could run to get all of the variables, do you have to call them like this:
$variable = $_REQUEST['variable'];
EDIT:
I'm going with $_POST as recommended by everyone here - thanks for the input! I'll just manually go through and write a line for each $_POST I have.
You can loop over all veriables in the $_PREQUEST array:
foreach($_REQUEST as $key=>$value){
//doStuff
}
However this will include all send parameters, not only the input. Also you should not use $_REQUEST but $_POST or $_GET
If you don't want to have hundreds of uniquely named variables and want to have arrays of data turn up client side, there is a handy form trick you may want to try.
<form>
<input name="foo[a]" type="text" />
<input name="foo[b]" type="text" />
<input name="bar[]" type="text" />
<input name="bar[]" type="text" />
Client Side:
<?php
$_POST['foo']['a'];
$_POST['foo']['b'];
$_POST['bar'][0];
$_POST['bar'][1];
?>
echo "<pre>";
print_r($_POST); // or $_GET
echo "</pre>";
If you are dealing with items that you possibly won't know the name of but need the values then you are dealing with a much larger problem than you think.
But the above snippet should show you all variables set and their values when you submit the form
I think you should start out with a list of all variables that you expect, and loop only over those. If you don't, hackers can inject any variable name... In fact, you're reemplementing the old, terribly bad idea of Register Globals. So, don't do that...
In fact, why not keep the input in an associative array, just like $_POST? You might still want to remove those values that you didn't expect.
As in my comment above, don't use REQUEST, use POST. I'd probably write a line for each one so that I was aware of what was happening. You don't want people to post extra variables that still get parsed.
You can write simple code to algorithmically obtain all inputs from a posted form, but this is a dangerous business, one that is ripe for exploitation.
The $_GET and $_POST array variables contain every parameter passed via URL or POST method respectively. You should rather use that variables instead of extracting every item like the register_globals option or extract function does. See Using Register Globals for the reasons.
I can't add a comment on Pim Jager's post, but here's an example code:
foreach($_POST as $key=>$value) {
echo($key.' > '.$value.'<br />');
}
Use an array with the fields you want copied from POST and store the data in an array. It's a lot easier to maintain.
$fields = array("name","email","addr","bla","bla2");
$form = array();
foreach($fields as $field){
$form[$field] = $_POST[$field];
}
Now you've got all the data inside $form.
You could also make a similar thing when creating the form. (Although it's trickier..)
Cheers!
foreach($_POST as $key=>$value) {
${$key} = $value;
}
but this does the same thing as extract()