How to create a PHP script that can handle multiple forms
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 开发者_StackOverflow社区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
精彩评论