Everytime I create a website for a client, I write the form HTML and then write the php script to handle that data. Sometimes the forms are long, sometimes there are multiple forms - it can get messy.
Before I begin to try and write my dynamic php form handler I'd really like some best practice advice and tips.
I thought of gathering all of the posted variables into an array to handle them. But then how do I know which values were supposed to be required or what they mean?
Maybe something already exists to fix this problem!
Thanks a lot,
Henry
Just a bit more info, what I have in mind is a php script which is flexible enough to work with any form built for it with any amount of inputs. I guess I see it as one file that sits on the server and multiple forms will be sending Ajax requests to it, which it can then satisfy
I don't think you should go with arrays, since the $_POST is already an array anyway.
But what about some sort of naming convention in your code?
ex:
<input type="text" name="txt_username" /> //prefix txt or whatever seems fitting.
Then use regular expressions to find what type of data you expect and act accordingly. You could for example write a class that handles different sorts of input and depending on the prefix in the name-property pass the data to the correct function.
Change the name of you submit button according to your form name. Then in php use a conditional statement to determine which form is posted and get your php working aas you wanted for different forms.
something like this
<input type="submit" name="signupform"/>
in php
if(isset($_POST['signupform']))
{
//Do this
}
elseif(isset($_POST['loginform']))
{
//do this
}
known issue:
You will need to keep those submit names unique and there should not be any other for element in any form being posted to that php file.
You can also add a hidden field
<input type="hidden" name='action' value='signup'/>
and then use a switch case with $_POST['action'] key.
I find it helps to seperate form parts by assigning them to an array e.g.
<input type="text" name="Users[username]" id="Users_username" />
That way, I can easily pick out sections by accessing the array key in php e.g.
$_POST['Users']; // returns username from above example
Related
Can we somehow pass the type HTML input attribute value to the $_POST array or grab it anyhow else with PHP?
I am aware that I can create a hidden field and basically put the type of the real input into the value of the hidden field, but this seems a bit like "repeating" work to me.
I want to create a Form, where input values are submitted to the $_POST and I can detect the type of that input without the need to hardcode/map the single inputs to each a type.
In this way I could detect the field type and act upon without the need to create a "map" that maps my custom inputs (by name or ID) to a certain type, which I already declare in HTML form anyway.
It seems a real shortcoming that the type of an input is undetectable in a Form Submit - or perhaps (hopefully) I miss something?
Can we somehow pass the type HTML input attribute value to the $_POST array or grab it anyhow else with PHP?
Not per se.
I am aware that I can create a hidden field and basically put the type of the real input into the value of the hidden field
That is a way to do it.
It seems a real shortcoming that the type of an input is undetectable in a Form Submit
Usually you know what type of data you expect for a given field because you aren't processing them generically, so it would rarely be a useful feature.
perhaps (hopefully) I miss something?
No.
Well here is the breakdown;
GET accessed via $_GET in PHP tackling and POST accessed via $_POST in PHP are transport methods, so is PUT, and DELETE etc for a from it does not matter what method you use it only works on client side and only knows to map every thing in it into serialised query string or at least have it read for being serialised.
For example
<input type="text" id="firstname" name="fname">
it takes the name attribute and converts into this
?fname=ferret
See it didn't even bother with ID attribute. When we hit submit button form will only run through name attributes of each input and make LHS of the with value and add user input as RHS to the value. It will not do anything else at all.
On PHP side we ask $_GET tunnel are there any query strings in the request or $_POST tunnel. Each of these if there is any query string - emphasis on word string. explodes the string into array and gives it you. hence $POST['fname'].
Looks something like this
$_POST = [
fname => 'ferret',
someothingelse => 'someothervalue']
SO what you are trying to do is or at least asking to do is ...make browser change its BOM behaviour - which we cannot in real sense of the matter; to make form add some thing like this.
?fname=ferret,text
?fname=ferret-text
?fname=ferret/text
form by default will not do this, unless you run custom function updating each query before submit and that is pron to what we call escaping, 3/100 time you would miss it given the chance
Then on PHP side you want PHP to figure out on its own that after slash is type like so
$_POST = [
fname => 'ferret/text']
PHP would not do that on its own, unless you fork it make custom whatever like Facebook has done and then run it or at least make some kind of low level library but that too would be after the fact.
in case your not wondering, thats how XSS and injections happen.
SO query string standards are rigid to keep things a string with militaristic data and serialised.
So yes what you intended to do with hidden field is one tested way of achieving what you are want.
I have a form (right now only one, but there will be more with similar parameters) and I validate it using jQuery Validation (it is too big word, I validate only one field using jQV), this form is send using AJAX. I have in this form 5 inputs:
text input: username, which is validated by separate PHP script remotely - it checks if this user exists in database of different site and if so, also checks if this user has some specified data, but this is not really important
2 times radio buttons (i mean 2x 2 radio buttons) which are validated in PHP (code later)
2 times PickAColor forms, which are also validated using PHP only with regexp for hexcolors
And I have a question. Is there any way to check this data in PHP in more, well, sophisticated way? Because, as I said, I validate them in similar way:
if($period != "3month" && $period != "7day") {
echo '<div class="alert">Wrong period!</div>';
exit;
}
Actually this form I am writing right now is rather short, but I also have some really big ones, and if's like this one above can take even 50 lines, and that pretty sucks. Most of them has similar expressions inside if, which means that I check if value sent by form is on the list of possible options provided by form (someone can change value parameters in Firebug and call himself hacker...). It's complicated and I don't know how to said that, but I think you understand me. So, once again - is there any sense to validate it in PHP and if so, is there any better way to validate it? Or maybe you have some other suggestions? Thanks a lot for your help.
Man you have to think your users can submit anything there, and to make the code clearer and more MVC oriented (and reusable) you need your validations in the app side, and generic functions in jQuery to just display errors to your users, so I would recommend you to do ajax post with the form sent to your php application, to an api controller that recives the form values, validates using the model and returns the object with the jew form values (if you need to clean up) and any error per field, then you just output in json :
{
errors: {
name: "Already used name",
field2: "Some bad text provided"
}
}
Then you just loop through the errors and set to the already existent placeholder of each error text like
<spam id="name-error" class="error"></spam>
<input type="text" name="name" value=""/>
Then you have a validation code that you can reuse when the form is submitted.
What I'm trying to achieve is, if there is an non empty input + another input will show up.
This is how the input looks like.
<input type="file" name="image[]" />
What I'm trying to do is something like this
if (!empty($input)){
//Add another input
}
I think that you can get the idea, I am just wondering is this achievable, since I am new in php I don't know if this is possible.
And I'm sorry if I made any grammatical mistakes English is not my native language.
Sure! By looking at $_POST and $_FILES you can get an idea whether the input contained something or not. Then you can make that if and render an additional <input> as necessary.
Note though that PHP is server side code. It runs when the form is submitted in the browser and thus the browser makes a request to the server. If you want the additional input to appear immediately, as soon as the first input is filled, you'll need to use JavaScript. That's also quite possible.
My guess is, you want interactivity. In which case, you will need to use JavaScript, which is a client side language.
You hook an event to the input, and check each time it's changed to see if it's empty. If it is, you display another input.
You can see if the file was empty by using:
if ($_FILES['image']['size'] > 0)
I have two forms on the page. To the user it looks like 1 form, and I actually wish it was one form. But the way I'm trying to reuse code and include things, I can't avoid two forms in the source code... trying to act as one.
I don't want to do ajax submit, I want a normal post submit, my form handler has redirects in it. How can I submit both of these, and get values that make sense on the server side. something like $_POST['form1]['whatever'] $_POST['form2]['thing']
Maybe take all the inputs from form 2, rename all of them with a prefix, and append them to form 1? I can't find a non-messy way of doing this. I don't think I need code, just a plan. Least messy idea wins.
Maybe take all the inputs from form 2, rename all of them with a
prefix, and append them to form 1?
That's exactly what you have to do. Wouldn't be much of an answer without a code sample, so here you go.
$("#form2 :input").appendTo("#form1")[0].submit()
now in php you'll have $_POST['thing'] containing an array with two values. Alternatively you can rename all of the inputs from form2:
$("#form2 :input").attr("name",function(name){
return name + "_form2";
}).appendTo("#form1")[0].submit();
You can try to collect values of one form with jQuery.serializeArray() and then generate hidden inputs with names and values from variable storing result of previously called jQuery.serializeArray() and insert them to second form on submit event of form.
You should be able to combine both forms fields into one single form in PHP. If your code doesn't allow it, it must be in terrible shape.
If you are using simple scripts, you should be able to cut the forms into parts producing the fields, and the other parts producing the form outlines, either as separate scripts, or simply as separate functions.
i.e.:
<?php
function form_body($params) {
// here's the code for echoing fields according to $params
}
function form($params) {
// here's the code to build the form properties
$f_properties = '....';
echo '<form '.$f_properties.'>';
form_body($params);
echo '</form>';
}
?>
Then it's just a matter of combining $params from form1 and form2 to get the definitive form.
If you're using OOP, it's probably very easy to derive a new class containing both forms, and have it output their fields.
This are very simplistic advices, but you don't provide any source to help refactoring, so I can only provide vague/generic code examples.
Going the js way to combine forms on the client side will turn into a lot of problems down the line to maintain and evolve the code, and bring a lot of issues (security not the least of them).
I'm writing, for the first time in PHP, a script to process a POSTed form that contains checkboxes.
As you know, checkboxes are grouped by using the same name attribute, and when multiple values occur, $_POST["some_name"] should be storing those in an array.
I tested but instead of the expected array I got one single value -- that of the last checked item.
At this point, somewhat puzzled, I look at some doc to discover that with PHP the checkbox name should end with []. Is that so? What crazy relation is there expected to exist between an HTML form and a script that processes it? Suppose I don't have access to the HTML field names? Suppose, as it is my case, I have every good reason not to alter my naming scheme just for some obscure nonsense.
Now, it seems there exists at least one solution to the issue: PHP: Retrieving value of checkboxes when name doesn't have array
I'd like to know if there's a really simple way to do without those crazy brackets, and, incidentally, your opinion on this point? Am I the only one shocked?
EDIT : OK, I can certainly work my way around this issue, but I hoped to be raising some (minor yet) fundamental point regarding some sort of "non-separation of concerns" between HTML and PHP. Obviously, that's none of PHP's business how HTML code should be written.
In your html code for the checkboxes:
name="mycheckboxname[]"
You should try with
<input type="checkbox" name="mycheckbox[]" value="Male" />
<input type="checkbox" name="mycheckbox[]" value="Female" />
In php side,
$myCheckBoxCollection = $_REQUEST['mycheckbox'];
What is your good reason for not incorporating [] in your naming scheme ? I don't think this is particularly shocking. As far as PHP is concerned, maybe you actually were expecting to only get the value from the last element with that particular name.
There are some alternatives such as the one you included in your question, or fetching the values with some javascript trickery, but I don't think you will find any that's easier than simply adding brackets to the name of your checkboxes.