PHP - Validating First Name
How much should you validate a First Name?
This is my code... // Validate First Name. if (empty($trimmed['firstName'])){ $errors['firstName'] = 'Please enter your First Name.'; }else{ if (preg_match('#^[A-Z \'.-]{2,20}$#i', $trimmed['firstName'])){ $firstName = $trimmed['firstName']; }else{ $errors['firstName'] = 'First Name must be 2-20 characters (A-Z \' . -)'; } } I did this for fear if I left things wide-open it would be a security risk. And in the U.S. at least, the above would really cover all valid First Names. Thoughts? Debbie Similar TutorialsHi, I have a user system where people login to my site with their emails. The thing I am after is when a person is registering I want to validate that they have entered a valid email with @.com in the string and not just some repetitive characters e.g. wwwwwww. Could some one guide me what is the best way to check for a valid email and for repetive characters in any given field examle firstname. One last thing I would also like to check that a person only enters Alphabets for name and stuff. Hello all, I need your help again. I have this page where the user inputs data: <?php include "include/dbc.php"; include "include/header.inc"; #error checking will go here ?> <style type="text/css"> .mydate{ color:#00F; text-decoration:underline; cursor:pointer; } </style> <script type="text/javascript"> function displayDate(d){ var date=new Date(); var D=date.getDate(); date.setDate(D+d); var YYYY=date.getFullYear(); var MM=date.getMonth()+1; MM<10?MM='0'+MM:null; var DD=date.getDate(); DD<10?DD='0'+DD:null; var span=document.getElementById('date'); span.innerHTML= 'Entries for '+MM+'/'+DD+'/'+YYYY; } onload=function(){displayDate(0)}; </script> <h1>Food Diary</h1> <div class="full"> <center><div><span class="mydate" onclick="displayDate(-1)"><img src="images/left_arrow.png" border="0">Yesterday</span> <span id="date" style="font-size:2em;"></span> <span class="mydate" onclick="displayDate(1)">Tomorrow<img src="images/right_arrow.png" border="0"></span></div><br /> <a href="#" onclick="displayDate(0);return false;">Today</a> </center> <div class="full"> <form name="exercise" id="exercise" method="GET" action=""> <center><table> <tr> <td><h3>Add an Activity</h3></td> </tr> <tr> <td><input name="NewSearchString" style="width: 100px" type="text"/> <input type="submit" value="Search" /> </td> </tr> <tr> <td> <select name="activity"> <option value="_">Activity Browse...</option> <option value="all">All Activities</option> <option value="biking">Biking</option> <option value="condition">Conditioning</option> <option value="dancing">Dancing</option> <option value="fish">Fishing & Hunting</option> <option value="Home">Home Activities</option> <option value="misc">Miscellaneous</option> <option value="music">Music Playing</option> <option value="occupation">Occupation</option> <option value="running">Running</option> <option value="sports">Sports</option> <option value="walking">Walking</option> <option value="water">Water Activities</option> <option value="winter">Winter Activities</option> </select> <input type="submit" value="Submit" /></td></tr></table></center></form> </td> </tr> </table> </center> <table width="100%"> <tr bgcolor="#66CC33"> <td><div>Activity</div></td> <td><div>Specific Activity</div></td> <td><div>Time (hh:mm)</div></td> <td><div>Distance</div></td> <td><div>Units</div></td> </tr> <tr bgcolor="#66CC33"> <td><div></div></td> <td><div></div></td> <td><div></div></td> <td><div class="Float"></div></td> <td class="cp_Distance"><div></div></td> </tr> <?php if(isset($_GET[activity])) { $category=$_GET[activity]; $result = mysql_query("SELECT * FROM exercise WHERE type='$category'"); ?> <form action="add_activity.php" method="POST"> <?php while($row = mysql_fetch_array($result)) { echo '<tr><td><div>'.$row[Type].'</div></td>'; echo '<td><div>'.$row[Name].'<input type="hidden" name="exerciseid[]" value="'.$row[Name].'"></div></td>'; echo '<td><div><input type="text" name="duration['.$row['Name'].']"></div></td>'; echo '<td><div><input type="text" name="distance['.$row['Name'].']"></div></td>'; echo '<td><div><select name="metric[]"> <option value=""></option> <option value="mile">mile</option> <option value="Km">km</option> <option value="M">m</option>; <option value="Yard">yrd</option> <option value="Feet">ft</option> </select></div></td></tr>'; echo'<input type="hidden" name="submitted" value="1">'; } mysql_close(); ?> <tr><td colspan="6" align="center"><input type="submit" name="submit" value="Add Activities" onClick="return confirm( 'Are you sure you want to submit the activities?');"></td></tr> </form> <?php } ?> <tr bgcolor="#66CC33"> <td><div></div></td> <td><div></div></td> <td><div></div></td> <td><div class="Float"></div></td> <td class="cp_Distance"><div></div></td> </tr></table> <div></div> <?php include "include/footer.inc"; ?> I want to validate that the user enters data for at least one of all the fields provided (distance, duration, metric). If someone could help me get started I'd greatly appreciate it. Hello.. I have Two HTML form and one is a Check boxes form that enable users to select their category. Then I need to display second form according to the categories they selected in first form. I use this code in first form to validate form submission.. if ( isset( $_POST['category']) && sizeof( $_POST['category']) <= 3) { $category = $_POST['category']; } else { $errors[] = 'Please select atleast 1, not more than 3 categories'; } If errors array is empty I did this.. if ( empty( $errors )) { // If everything's OK $_SESSION = $category; $url = 'http://localhost/lanka_institute/tutorsignup/select_subjects.php? // Define the URL. ob_end_clean(); // Delete the buffer. header("Location: $url"); exit(); // Quit the script. } Can I know and is this correct? I display category list from mysql category table, it has category name and category id this is my html part from first page echo '<td width="50%"><input type="checkbox" name="category[]" vlaue="' . $info['category_id'] . '" /> ' . $info['category_name'] . '</td>'; any help appreciated. Thanks in advance.. Hi all, Hi have a bit of a problem that I am completely stuck on. I have a form on a website that needs checkboxes to be processed by PHP, but i have no idea how to implement them. I have found examples, but my knowledge of php is exactly zero, so its confusing the hell out of me. The website is: http://www.geelongnannies.com.au/test/employment.html http://www.geelongnannies.com.au/test/freecontactformprocess3.php http://www.geelongnannies.com.au/test/freecontactformsettings.php if anyone can have a look and give me an example of how to change the php to process the checkboxes when submitted, I will be very grateful cheers! This topic has been moved to Other Programming Languages. http://www.phpfreaks.com/forums/index.php?topic=347582.0 I have the following code below to validate a date that the user types in. But I am getting the following error: "Warning preg_match() [function.preg-match]: Unknown modifier '('" Code: [Select] if(!empty($_POST['exp_date'])) { $pattern = '(^[0-9]{1,2})' // 1 or 2 digits .'([^0-9a-zA-Z])' // not alpha or numeric .'([0-9]{1,2})' // 1 or 2 digits .'([^0-9a-zA-Z])' // not alpha or numeric .'([0-9]{1,4}$)'; // 1 to 4 digits $exp_date = trim($_POST['exp_date']); if(preg_match($pattern, $exp_date)){ $pattern = '(^[0-9]{1,2})' // 1 or 2 digits .'([^0-9a-zA-Z])' // not alpha or numeric .'([a-zA-Z]{1,})' // 1 or more alpha .'([^0-9a-zA-Z])' // not alpha or numeric .'([0-9]{1,4}$)'; // 1 to 4 digits if (preg_match($pattern, $exp_date)){ $pattern = '(^[a-zA-Z]{1,})' // 1 or more alpha .'([^0-9a-zA-Z])' // not alpha or numeric .'([0-9]{1,2})' // 1 or 2 digits .'([^0-9a-zA-Z])' // not alpha or numeric .'([0-9]{1,4}$)'; // 1 to 4 digits if (preg_match($pattern, $exp_date)){ $pattern = '(^[a-zA-Z]{1,})' // 1 or more alpha .'([0-9]{2})' // 2 digits .'([0-9]{4}$)'; // 4 digits if (preg_match($pattern, $exp_date)){ $pattern = '(^[0-9]{4})' // 4 digits .'([^0-9a-zA-Z])' // not alpha or numeric .'([0-9]{1,2})' // 1 or 2 digits .'([^0-9a-zA-Z])' // not alpha or numeric .'([0-9]{1,2}$)'; // 1 to 2 digits if (preg_match($pattern, $exp_date)){ $pattern = '(^[0-9]{2})' // 2 digits .'([0-9]{2})' // 2 digits .'([0-9]{4}$)'; // 4 digits if (preg_match($pattern, $exp_date)){ $pattern = '(^[0-9]{4})' // 4 digits .'([^0-9a-zA-Z])' // not alpha or numeric .'([a-zA-Z]{1,})' // 1 or more alpha .'([^0-9a-zA-Z])' // not alpha or numeric .'([0-9]{1,2}$)'; // 1 to 2 digits } else { $errors[]= 'Please enter a valid expiration date.'; } } else { $errors[]= 'Please enter a valid expiration date.'; } } else { $errors[]= 'Please enter a valid expiration date.'; } } else { $errors[]= 'Please enter a valid expiration date.'; } } else { $errors[]= 'Please enter a valid expiration date.'; } } else { $errors[]= 'Please enter a valid expiration date.'; } } else { $errors[]= 'Please input an expiration date.'; } Hi, what is they best way to validate user input of strings? A couple of examples would be : 1> If i wanted to check for the existance on the coma ',' character in a string and replace it with a dash '-' character? 2> To check wether a user has entered a valid ip address in the form of x.x.x.x where x can range from 0-255? I think i may need ereg/preg to do this but i have no idea about how to layout the syntax. Thanks for looking. Hello, I am trying to validate my form using php and would like some advice as this is the first time I have attempted this. I have a script which runs when the user clicks the submit button. What I am trying to do is validate the user input before inserting it into the database. This is the script: [font=monospace]<?php session_start(); $dbhandle = mysql_connect('localhost', 'root', '') or die("Unable to connect to MySQL"); $selected = mysql_select_db("commentdatabase",$dbhandle) or die("Could not select the database"); $name = check_input($_POST['fname']); $loc = check_input($_POST['loc']); $com = check_input($_POST['com']); function check_input($data) { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); return $data; } $sql = "INSERT INTO userinfo (name, location, comment) VALUES ('{$name}','{$loc}','{$com}')"; if(!mysql_query($sql, $dbhandle)) { die('Error: ' . mysql_error()); } header('Location: ../contact.php'); mysql_close(); ?> [/font] What's happening is that when it is submitted to the database, it is displaying < and > characters as < and >. Yet once being redirected with the header function the input is displayed with the < and > signs. I'm not sure if the function in the action script is in the wrong place or not. I have tried moving it around above and below the post variables. Just looking for a bit of advice really. Thank you, Regards, BuNgLe OK, so one of my cameras includes a "Copyright" field in the array returned from the exif data and one doesn't. Does anyone have any ideas how one would test for this field, and if it doesn't exist fill the relevant variable with the copyright info. I have been trying to solve this for a couple of hours now without a great deal of success, what I have is:- Code: [Select] $exif = exif_read_data('thistle.jpg', 'EXIF'); $name = $exif['FileName']; $height = $exif['ExifImageWidth']; $width = $exif['ExifImageLength']; $copy = $exif['Copyright']; $model = $exif['Model']; $exposuretime = $exif['ExposureTime']; $fnumber = $exif['COMPUTED']['ApertureFNumber']; $iso = $exif['ISOSpeedRatings']; $date = $exif['DateTime']; echo "File Name: $name<br />"; echo "Comment: " . $exif['COMMENT'][0] . "<br />"; echo "Height: $height<br />"; echo "Width: $width<br />"; echo "Copyright: $copy<br />"; echo "Camera: $model<br />"; echo "Shutter Speed: $exposuretime<br />"; echo "F number: $fnumber<br />"; echo "ISO: " . $iso . "<br />"; echo "Date & Time: $date<br /><br />"; Whatever I try always seems to end with "Notice: Undefined index: Copyright in C:\wamp\www\php\exif-read.php on line 11" it is obviously Code: [Select] $copy = $exif['Copyright'];that is causing the problem, and I can't work out just how to test for the existence of "Copyright" and head this problem off... Hi All, I'm trying to validate file types and keep seeing an error. I only allow .gif, .jpg or .png. However, if I upload any of those file types, I get an error message.... If I echo out $filetypeCheck, I get image/png, which is corrent... Code: [Select] $filetypeCheck = $_FILES["file"]["type"]; if( ($filetypeCheck != "image/gif") || ($filetypeCheck != "image/jpeg") || ($filetypeCheck != "image/png") ) { $val_error[] = 'File Type Error! (.gif, .jpg and .png only)'; } Whats going on here? i'm trying to an if statement so that a piece of code is only executed if a returned variable equals a letter in the alphabet(any letter) the variable is from a $_GET, and all i want to check is if the variable contains a letter. This is what i have so far, but it doesnt work $sort=$_GET[orderby]; if ($sort=="[A-Z]") { $read=mysql_query("SELECT * FROM films WHERE title LIKE '".$sort."%'") or die(mysql_error()); $result=mysql_num_rows($read); } else { $read=mysql_query("SELECT * FROM films ORDER BY title") or die("query failed"); $result=mysql_num_rows($read); } Any help would be great. Hi Guys Can anyone tell me why this doesn't work? Code: [Select] <?php $form = "<form action='test.php' method='POST'><input type='text' name='test' /> <input type='submit'>"; echo $form; $name = $_POST['test']; class validate { function check_input($data) { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); return $data; } } $z = new validate(); echo $z->check_input($name); ?> Also, when it comes to validating POST data that's input via a form and retrieving it is it secure to set a variable for the Post i.e. Code: [Select] $name = $_POST['test']; or is more secure to pass Code: [Select] $_POST['test'] straight into the validation? It just occurs to me if you pull the post into a variable then you're inviting insecure code into your script. Though i am a complete noob at this so might be talking rubbish! Any light you can shed on why my little script isn't working would be appreciated and any tips on the best method for validating data securely would also be welcome Thank you Drongo This topic has been moved to JavaScript Help. http://www.phpfreaks.com/forums/index.php?topic=310792.0 A form on my website uses several drop down boxes. One to select an id number from a list retrived by a query. The others to get a start and stop time. Using two for each, one for hours, one for minutes. I already have some validation code which works fine, however, I can't seem to be able to use > or < mathematical signs with the times (ie, the start time must be < than the stop time). Also, I have Code: [Select] value="<? echo $name; ?>" in each of the fields to re-insert the data as it gets erased if the form isn't correct. How do I do the same for the drop downs? I hope this makes sense. Code: [Select] <? // only validate form when form is submitted if(isset($Submit)){ $error_msg=''; if(trim($starttime)==(trim($stopttime))) { //drop down $error_msg.="starttime cannot equal stop time.<br>"; } if(trim($starttime)>(trim($stopttime))) { //drop down $error_msg.="starttime cannot be greater than stop time.<br>"; } if(trim($startfuel)<(trim($stopfuel))) { //text field $error_msg.="Departure fuel cannot be less than arrival fuel<br>"; } if(trim($id)=="sca") { //query powered drop down (this one works, but doesn't re-select the option $error_msg.="Please select the id number.<br>"; } http://southerncrossairlines.ausvirtual.com/New%20Site/Complete/validation/Untitled-1.php I am debugging a PHP file that validates a user registration form. I'm very confused on this error message I'm receiving. ( Parse error: syntax error, unexpected '[' in C:\wamp\www\reg.php on line 17 ) I have looked until I cross-eyed to finf the syntax error. Here is a copy of my code: <?php // Post registration to database // Connects to your Database $userName = "taft65_admin"; $passWord = "taft65_paris4505"; $host="localhost"; $dbName = "taft65_members"; mysql_connect("dbName", "userName", "passWoord", "host") or die(mysql_error()); mysql_select_db("dbn") or die(mysql_error()); //This code runs if the form has been submitted if (isset($_POST['submit'])) { [color=yellow]//This makes sure they did not leave any fields blank if (!$_POST['id'] | !_POST['userName'] | !$_POST['passWord'] | !$_POST['confpassWord'] | !$_POST['email'] ) { die('You did not complete all of the required fields'); }[/color] // checks if the userName is in use if (!get_magic_quotes_gpc()) { $_POST['userName'] = addslashes($_POST['userName']); } $usercheck = $_POST['userName']; $check = mysql_query("SELECT userName FROM users WHERE userName = '$usercheck'") or die(mysql_error()); $check2 = mysql_num_rows($check); //if the name exists it gives an error if ($check2 != 0) { die('Sorry, the userName '.$_POST['userName'].' is already in use.'); } // this makes sure both passWoords entered match if ($_POST['passWord'] != $_POST['ConfPassWord']) { die('Your passWoords did not match. '); } // here we encrypt the passWord and add slashes if needed $_POST['passWord'] = md5($_POST['passWord']); if (!get_magic_quotes_gpc()) { $_POST['passWord'] = addslashes($_POST['passWord']); $_POST['userName'] = addslashes($_POST['userName']); } // now we insert it into the database $insert = "INSERT INTO registration (userName, passWord, email ) VALUES ('".$_POST['userName']."', '".$_POST['passWord'].", '".$_POST['email']."')"; $add_member = mysql_query($insert); ?> <p>Thank you, you have successfully registered. <a href="memPage.html"></a>you may now login.</p> Can someone help me with this by checking the code and tell me where I wen in error. BobLan66 <?php $SQL = "SELECT stu_satisfaction_tblquestions.question_id, stu_satisfaction_tblquestions.question, answer_type.* FROM stu_satisfaction_tblquestions LEFT JOIN answer_type ON stu_satisfaction_tblquestions.answers_id=answer_type.answers_id WHERE stu_satisfaction_tblquestions.answers_id BETWEEN '1' AND '2' "; $result = mysql_query($SQL); while ($data = mysql_fetch_array($result)) { echo $data['question'].'<br/>'; echo '<input type="radio" name="answers['.$data['question_id'].']" id="'.$data['question_id'].'_'.$data['answer1'].'" value="1" /><label for="'.$data['question_id'].'_'.$data['answer1'].'">'.$data['answer1'].'</label><br/>'; echo '<input type="radio" name="answers['.$data['question_id'].']" id="'.$data['question_id'].'_'.$data['answer2'].'" value="2" /><label for="'.$data['question_id'].'_'.$data['answer2'].'">'.$data['answer2'].'</label><br/>'; echo '<input type="radio" name="answers['.$data['question_id'].']" id="'.$data['question_id'].'_'.$data['answer3'].'" value="3" /><label for="'.$data['question_id'].'_'.$data['answer3'].'">'.$data['answer3'].'</label><br/>'; echo '<input type="radio" name="answers['.$data['question_id'].']" id="'.$data['question_id'].'_'.$data['answer4'].'" value="4" /><label for="'.$data['question_id'].'_'.$data['answer4'].'">'.$data['answer4'].'</label><br/>'; echo '<input type="radio" name="answers['.$data['question_id'].']" id="'.$data['question_id'].'_'.$data['answer5'].'" value="5" /><label for="'.$data['question_id'].'_'.$data['answer5'].'">'.$data['answer5'].'</label><br/>'; } ?> this is my form, how should i validate the radio buttons of it? I'm trying to add an email validation into the code so that it pops up with a similar message as the others if you don't use the @ or .com in your email address and it just ignores it and keeps sending the email anyways no matter what i put into the email field. here is the php i have for it i'm sure it's something really simple but i am not as familiar with php as i would like to be...
When i try and test this to make sure it works it only gives me the message that my email has been sent and i want it to not send if the email address doesn't have the @ sign or the .com or whatever kind of website it's from. I bolded the code that is not working the way i want it too.
<?php
if ($_POST['submit']) { Hey, I have a script which processes an image when it is uploaded, but now i have a new form that allows users to upload four images at a time. I store them in an array in the form like so: name="file[]" So now i am wondering how do i process each image with a forloop because using $_FILES doesn't say which image to check in the array? Hope some one can help me! Heres my code: Code: [Select] <?php if(isset($_POST['submit'])){ echo '<p align="center">'; if ($_FILES["file"]["size"] < 1000000) { if ($_FILES["file"]["error"] > 0) { echo "Return Code: " . $_FILES["file"]["error"] . "<br />"; } else { $filename = $_FILES["file"]["name"]; if (file_exists("images/".$name."/".$filename)) { echo "Image already uploaded!"; } else { if (is_dir("userimages/".$name) == FALSE){ mkdir("images/".$name, 0777); } move_uploaded_file($_FILES["file"]["tmp_name"], "userimages/".$name."/" . $filename); echo "Image has been uploaded!"; } } } else { echo "Invalid file"; } } ?> Thanks Does anyone know how I can validate US currency using php that is entered into a textbox? The textbox is setup as a decimal in mysql and i'm trying to make sure only decimals are entered so when php calculates the values entered I don't receive errors. Hi all, Im creating a simple quiz where some of the questions are checkbox because there is more than one correct answer. What I would like to be able to do, is run an if statement to check if, say for example, options 1 and 5 out of 6 have been selected, then award the point. However the point is only awarded is both options are selected. Any suggestions? Thank you in advance |