When I develop forms which require processing in PHP I tend to put the form and PHP into a single file e.g. signup.php and use the $_GET method to figure out what I need to do with the form.
For example, if /site/signup.php is requested then I know I need to display the HTML form, but if /site/signup.php?action=newsignup is requested (by the html form submit) then I know I need to process it.
I have been quite happy with this approach as it means I need to maintain less files and that everything which interacts is in one file which makes tracing problems easier (plus I hate sites which continully redirect from page to page when processing data.)
A rough example of what I would do is :
<?php
if (isset($_GET['action'] && $_GET['action'] == "newsignup")
{
$name = cleanInput($_POST['name'];
$email = cleanInput($_POST['email'];
if(validUserName($name)== TRUE)
{
// do processing here
} else {
// fail processing here
}
if(validEmail($email)== TRUE)
{
// do processing here
} else {
// fail processing here
}
// Do database stuff etc
// Display success message
} else {
// Not $_GET so must be a new sign-up. Display html form
<form id="signup" action="signup.php?action=newsignup" method="post">
<input type="text" name="name" id="name" />
<input type="text" name="email" id="email" />
<input type="submit" id="submit" value="Submit" />
</form>
}
Now I am starting to use jQuery/Ajax to do the validation client-side to give feedback while the user is completing the form, when data is entered into a text box in the form the data is validated in real time using a keyup event to post that textbox to a .php script for validation. To do that I am using jQuery Post:
function name_check(){
var username = $('name').val();
if(name == "" || name.length < 4){
$('#name').css('border', '3px #CCC solid');
$('#text').text('');
}else{
$.post('jquerysignup.php', { name: $('#name').val()}, function(response) {
$('#phpout').html(response['message']); // return an error string if exists
if(response['returnval'] == 0){
$('#name').css('border', '3px green solid');
$('#submit').fadeIn('slow')
} else if (response['returnval'] == 2){
$('#name').css('border', '3px red solid');
$('#submit').fadeOut('slow')
} else {
$('#name').css('border', '3px red solid');
$('#submit').fadeOut('slow')
}
}, 'json');
} //
}
The file jquerysignup.php is contains only the PHP functions validUserName and validEmail.
I am now in the position where have have two .php files, one for the server-side validation and now one for the client-side. I want to keep both client-side and server-side validation but I do not want to keep multiple files which contain duplicate functionality.
I have been struggling find or come up with an integrated solution and I know there must be a better way to do do this but I cannot find any examples to deal with this specific problem.
I would really appreciate some guidance in a best practise / solution to this.