rfnel Posted June 1, 2011 Share Posted June 1, 2011 Hi Guys I'm pretty new to PHP, and I've taken on a small PHP project. My project has (among other things) a page where you can capture/edit users. This involves entering a user name and password on an HTML POST form. Upon submitting the form, the data is set to a php script that writes it to a MySQL database. My problem is this - I need to validate the data before writing it to the database. I have to check that all required fields have values, that the "Password" and "Confirm Password" fields match and that the user did not enter illegal characters (SQL injection). Where should this happen? The script can validate the data, but then I'll still need a way to send the user back to the form and repopulate it automatically with what the user had entered. I can't use GET parameters (due to having to keep the password private). One way of doing it might be to send everything except the password as GET parameters, and force the user to re-enter the password. Am I missing something here? What's the best way of doing validations? Thanks for your input. Cheers, Riaan Quote Link to comment https://forums.phpfreaks.com/topic/238138-where-how-to-do-validations/ Share on other sites More sharing options...
Pikachu2000 Posted June 1, 2011 Share Posted June 1, 2011 There's no one single correct way of validating data. It has to be validated based on the values that are allowed (or disallowed). Here is a fairly basic example of form validation and input error handling using arrays and some CSS. Copy it into a file and run it, see how it works, and make changes to it to see what the result is. <?php if( isset($_POST['submitted']) && $_POST['submitted'] == 'yes' ) { //check for hidden field value to indicate form has been submitted $errors = array(); // initialize an array to hold validation errors $_POST = array_map('trim', $_POST); // trim all $_POST array values if( !empty($_POST['name']) ) { // validate the name field if( !ctype_alpha($_POST['name']) ) { $errors['name'][] = 'Name must be alphabetic characters only.'; // if name has non alpha chars, store error } if( strlen($_POST['name']) < 3 || strlen($_POST['name'] > 20) ) { $errors['name'][] = 'Name must be from 3 to 20 characters.'; // if name has too many/few chars, store error } } else { $errors['name'][] = 'Name is a required field.'; // if name is empty, store error } if( !empty($_POST['number']) ) { // same validations as in name, above. if( !ctype_digit($_POST['number']) ) { $errors['number'][] = 'Number must be numeric.'; } if( strlen($_POST['number']) < 5 || strlen($_POST['number']) > 10 ) { $error = 'Number must be from 3 to 20 digits. It is currently ' . strlen($_POST['number']) . ' digit'; $error .= strlen($_POST['number']) == 1 ? '.' : 's.'; $errors['number'][] = $error; } } else { $errors['number'][] = 'Number is a required field.'; } if( !empty($errors) ) { // if the $errors array is not empty, display the errors to allow the user to correct them and resubmit the form $echo = array(); foreach( $errors as $v ) { if( is_array($v) ) { $echo[] = implode('<br>', $v ); } else { $echo[] = $v; } } $err_echo ="<font color=\"red\">The following errors were detected:<br>"; $err_echo .= implode("<br>\n", $echo); $err_echo .= '</font>'; } } if( (isset($_POST['submitted']) && !empty($errors)) || !isset($_POST['submitted']) ) { ?> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html;charset=utf-8" > <style type="text/css" media="screen"> body { font-family: helvetica, arial, sans-serif; font-size: 0.85em; line-height: 1.25em; letter-spacing: -0.5px; } input { border: 1px solid #336699; padding: 0.1em; margin: 5px; color: #113366; } input.error { background-color: #F2BDCA; color: #850310; border: 1px solid red; } input.good { background-color: #D3F5D3; border: 1px solid #156B15; color: #156B15; } input.submit { background-color: #CCCCCC; border: 1px solid #888888; color: #333333; padding: 2px; margin: 0; font: 0.9em helvetica, arial sans-serif; } </style> <title> Work In Progress</title> </head> <body> <?php echo !empty($err_echo) ? $err_echo : ''; ?> <form method="post" action=""> Name (3-20 letters): <input type="text" class="<?php if( isset($_POST['submitted']) ) { echo !empty($errors['name']) ? 'error' : 'good'; } ?>" name="name" value="<?php echo isset($_POST['name']) ? $_POST['name'] : ''; ?>"> <br> Number (5-10 numbers): <input type="text" class="<?php if( isset($_POST['submitted']) ) { echo !empty($errors['number']) ? 'error' : 'good'; } ?>" name="number" value="<?php echo isset($_POST['number']) ? $_POST['number'] : ''; ?>"> <br> <input type="hidden" name="submitted" value="yes"> <input class="submit" type="submit" name="submit" value=" <?php echo !empty($errors) ? 'Re-Submit' : 'Submit'; ?> "> </form> <?php } else { // Form was submitted, and validated with no errors. OK to run db insert, display success message, etc. echo "Successful submission!"; } ?> </body> </html> Quote Link to comment https://forums.phpfreaks.com/topic/238138-where-how-to-do-validations/#findComment-1223699 Share on other sites More sharing options...
rfnel Posted June 2, 2011 Author Share Posted June 2, 2011 Hi Pikachu Based on your example, it's perfectly fine to post a form to itself and do validations in the same script? My question was relating more to which script (same script or another script that only handles validations) should be used to perform the actual validation checks. I'm not a native English speaker, so I apologise if my question was ambiguous. Nonetheless, your script helped me to learn a couple of useful functions that I didn't know about. Thanks! I've decided to post the results to a script that does validations and inserts the data. If validations fail, the user be redirected to the original page to fix their input. Quote Link to comment https://forums.phpfreaks.com/topic/238138-where-how-to-do-validations/#findComment-1224229 Share on other sites More sharing options...
teynon Posted June 2, 2011 Share Posted June 2, 2011 rfnel, PHP is a server side language. That means the code is executed and results are created on the server side. Therefore, a user can not modify the output unless they alter form (POST) or URL (GET) variables. (Or session data.) This means it doesn't really matter what page you send them to in order to validate your information. As for a way to validate. A lot of people say that I shouldn't do this, but I do it anyways in addition to additional steps for specific types of variables.. I run a loop on all POST, GET, and SESSION variables and remove html special characters with the flag ENT_QUOTES. This creates a sort of blacklist for all input information. If something should be an integer, then obviously you need to do further validation to ensure that it is in fact an integer. An example of how I do this is: foreach ($_POST as $key=>$value) { $_POST[$key]=htmlspecialchars($value, ENT_QUOTES); } You can add an is_array check on multidimensional arrays to go further down the level if you need to accept them. Quote Link to comment https://forums.phpfreaks.com/topic/238138-where-how-to-do-validations/#findComment-1224237 Share on other sites More sharing options...
arbitter Posted June 2, 2011 Share Posted June 2, 2011 The handy thing about handling all the things in one page, is that you don't have to mess with all different files averywhere. I made a site with many forms in php, all being run on one page. The login, the register, the cookiehandling, password change, ... Ofcourse it has its disadvantages. The script gets larger and larger, and less 'clear' to you. Especially if ou havn't seen the script in quite a while and wish to make changes somewhere, you first have to dig down. Also, you have to see that every input and submit has a different name. And the site loads slower I guess, since it needs to go through all the if(isset($_POST['']))'s. But for me the pro's exceed the con's. For the validation I do the following: <?php function CleanMyDirtyData($dirtydata){ return mysql_real_escape_string(htmlentities($dirtydata, ENT_QUOTES,'UTF-8')); } if(isset($_POST['submitsomething'])){ if(empty($_POST['field1']) || empty($_POST['field2'])){ $_SESSION['melding'] = 'You must fill in those forms!'; header('Location: thissite.php'); exit(); } $field1 = CleanMyDirtyData($_POST['field1']); //and so on } ?> Quote Link to comment https://forums.phpfreaks.com/topic/238138-where-how-to-do-validations/#findComment-1224245 Share on other sites More sharing options...
teynon Posted June 2, 2011 Share Posted June 2, 2011 I would strongly disagree with arbitter, however. No offense intended, but usually when I see websites that are coded using one page, it is a sign of a rookie. Coding everything in one page can greatly hurt performance if your web site receives a lot of traffic. It also results in a less organized program. 20 lines of relevant code is much easier to understand than a couple thousand of code that might only be relevant to specific pages. I would say it is always better to have different files for different functions of your web site. Then you use includes to link repeating code. As for using a different file for validation, that is up to you because a form and validation could be seen as one function. Quote Link to comment https://forums.phpfreaks.com/topic/238138-where-how-to-do-validations/#findComment-1224250 Share on other sites More sharing options...
arbitter Posted June 2, 2011 Share Posted June 2, 2011 I would strongly disagree with arbitter, however. No offense intended, but usually when I see websites that are coded using one page, it is a sign of a rookie. Coding everything in one page can greatly hurt performance if your web site receives a lot of traffic. It also results in a less organized program. 20 lines of relevant code is much easier to understand than a couple thousand of code that might only be relevant to specific pages. I would say it is always better to have different files for different functions of your web site. Then you use includes to link repeating code. As for using a different file for validation, that is up to you because a form and validation could be seen as one function. No offence taken, I am a rookie! I only have one site which has had only 650 visits in about half a year, and I only have to make changes once or so. So it works for me! Quote Link to comment https://forums.phpfreaks.com/topic/238138-where-how-to-do-validations/#findComment-1224260 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.