PHP - Form Validation Data, Where Should I Put It?
Similar TutorialsI have a form on our website that a user can fill out for custom product. I want the form data to be 1) stored into a mysql database AND after storing said data, 2) email the same data to our sales department. 1) The form data DOES get stored into mysql database (except for the first two fields, for some weird reason) 2) I added a "mail" section to the php file that stores the data into the database, but it is not working correctly. I have stripped the email portion down to sending just one of the fields in the "message" to make it easier for troubleshooting I have included here, both the form section of the html file, and the formdata.php file that processes the data for your analysis. I am relatively new to php so there are going to be some issues with security, but I can work on those after I get the store & email process to work correctly. Please review my code and see if anyone can be of assistance. I looked through the forums and couldn't find another issue that was the same as mine. If I just overlooked, please tell me the thread post #. Thanks THE FORM WHICH COLLECTS THE DATA ******************************* <form method=POST action=formdata.php> <table width="640" border=0 align="center"> <tr> <td align=right><b>First Name</b></td> <td><input type=text name=FName size=25></td> <td><div align="right"><b>Telephone</b></div></td> <td><input type=text name=Tel size=25></td> </tr> <tr> <td align=right><b>Last Name</b></td> <td><input type=text name=LName size=25></td> <td><div align="right"><b>Fax</b></div></td> <td><input type=text name=Fax size=25></td> </tr> <tr> <td align=right><b>Title</b></td> <td><input type=text name=Title size=25></td> <td><div align="right"><b>Email</b></div></td> <td><input type=text name=Email size=50></td> </tr> <tr> <td align=right><b>Company</b></td> <td><input type=text name=Comp size=25></td> <td> </td> <td> </td> </tr> <tr> <td align=right><b>Address</b></td> <td><input type=text name=Addr size=25></td> <td><div align="right"><b>Estimated Annual Volume</b></div></td> <td><input type=text name=EAV size=25></td> </tr> <tr> <td align=right><b>City</b></td> <td><input type=text name=City size=25></td> <td> </td> <td> </td> </tr> <tr> <td align=right><b>State/Province</b></td> <td><input type=text name=SProv size=25></td> <td><div align="right"><b>Application</b></div></td> <td><input type=text name=Appl size=25></td> </tr> <tr> <td align=right><b>Country</b></td> <td><input type=text name=Ctry size=25></td> <td><div align="right"><b>Type of System</b></div></td> <td><input type=text name=Syst size=25></td> </tr> <tr> <td align=right><b>Zip/Postal Code</b></td> <td><input type=text name=ZPC size=25></td> <td> </td> <td> </td> </tr> <tr> <td align=right> </td> <td> </td> <td> </td> <td> </td> </tr> <tr> <td align=right> </td> <td><div align="right"><strong><font color="#FFFF00" face="Arial, Helvetica, sans-serif">COIL DESIGN</font></strong></div></td> <td><font color="#FFFF00" face="Arial, Helvetica, sans-serif"><strong>PARAMETERS</strong></font></td> <td> </td> </tr> <tr> <td align=right> </td> <td> </td> <td> </td> <td> </td> </tr> <tr> <td align=right><b>Primary Resistance (ohms)</b></td> <td><input type=text name=Pres size=25></td> <td><div align="right"><b>Primary Inductance (mH)</b></div></td> <td><input type=text name=Pind size=25></td> </tr> <tr> <td align=right><b>Secondary Resistance (ohms)</b></td> <td><input type=text name=Sres size=25></td> <td><div align="right"><b>Secondary Inductance (H)</b></div></td> <td><input type=text name=Sind size=25></td> </tr> <tr> <td align=right> </td> <td> </td> <td> </td> <td> </td> </tr> <tr> <td align=right><b>Peak Operating Current (Amps)</b></td> <td><input type=text name=POC size=25></td> <td> </td> <td> </td> </tr> <tr> <td align=right> </td> <td> </td> <td> </td> <td> </td> </tr> <tr> <td align=right><b>Output Energy (mJ)</b></td> <td><input type=text name=Egy size=25></td> <td><div align="right"><b>Output Voltage (kV)</b></div></td> <td><input type=text name=Volt size=25></td> </tr> <tr> <td align=right> </td> <td> </td> <td> </td> <td> </td> </tr> <tr> <td align=right><b># HV Towers per Coil</b></td> <td><input type=text name=TPC size=25></td> <td><div align="right"><b># of Coils per Package</b></div></td> <td><input type=text name=CPP size=25></td> </tr> <tr> <td align=right> </td> <td> </td> <td> </td> <td> </td> </tr> <tr> <td align=right> </td> <td> </td> <td> </td> <td> </td> </tr> <tr> <th colspan=4><b>Please enter any additional information he </b></th> </tr> <tr> <th colspan=4><textarea name=Mess cols=50 rows=10 id="Message"></textarea></th> </tr> </table> </dl> <div align="center"> <p> <input type=hidden name=BodyTag value="<body bgcolor="#484589" text="#FFFFFF" link="#FFFF00" alink="#FFFFFF" vlink="#FF7F00">"> <input type=hidden name=FA value=SendMail> </p> <p><font color="#FFFF00" face="Arial, Helvetica, sans-serif"><strong>PLEASE MAKE SURE ALL INFORMATION<br> IS CORRECT BEFORE SUBMITTING</strong></font></p> <p> <input type=submit value="Submit Form"> </p> </div> </form> THE FILE THAT PROCESSES THE FORM DATA (formdata.php) *********************************************** <?php $con = mysql_connect("localhost","XXX","XXX"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("customform", $con); $sql="INSERT INTO formdata (Fname, Lname, Title, Comp, Addr, City, SProv, Ctry, ZPC, Tel, Fax, Email, EAV, Appl, Syst, Pres, Pind, Sres, Sind, POC, Egy, Volt, TPC, CPP, Mess) VALUES ('$_POST[Fname]','$_POST[Lname]','$_POST[Title]','$_POST[Comp]','$_POST[Addr]','$_POST[City]','$_POST[SProv]','$_POST[Ctry]','$_POST[ZPC]','$_POST[Tel]','$_POST[Fax]','$_POST[Email]','$_POST[EAV]','$_POST[Appl]','$_POST[Syst]','$_POST[Pres]','$_POST[Pind]','$_POST[Sres]','$_POST[Sind]','$_POST[POC]','$_POST[Egy]','$_POST[Volt]','$_POST[TPC]','$_POST[CPP]','$_POST[Mess]')"; if (!mysql_query($sql,$con)) { die('Error: ' . mysql_error()); } echo "Your Information Was Successfully Posted"; mysql_close($con); $to = "recipient email address here"; $subject = "Custom Form"; $email = $_POST['Email'] ; $message = $_POST['Comp'] ; $headers = "From: $Email"; $sent = mail($to, $subject, $message, $headers) ; if($sent) {print "Your mail was sent successfully"; } else {print "We encountered an error sending your mail"; } ?> I wrote this code many moons ago... Code: [Select] if (preg_match('#^[A-Z \'.-]{2,20}$#i', $trimmed['firstName'])){ Can someone please help me remember... What do the two # signs do? Thanks, Debbie Hey guys.. I'm new to the forum and have a quick question about some coding i've been doing for my website. A couple index errors are coming up when I run my code, but I believe it all should be working fine. I am going to paste the code, but also upload the files so that you can understand the problem better. ANY help is greatly appreciated. I am currently making a contact form with validation. I know that using ifempty() is probably the best way, but I am unclear as to how to use it. I have two files, an html containing my form, and a php file containing the following code: //Define Variables $FirstName = $_GET['FirstNameTextBox']; $LastName = $_GET['LastNameTextBox']; $PhoneNumber = $_GET['PhoneNumberTextBox']; $EmailAddress = $_GET['EmailAddressTextBox']; $Address = $_GET['AddressTextBox']; $City = $_GET['CityTextBox']; $State = $_GET['StateDropDownBox']; $Zip = $_GET['ZipTextBox']; $error1='*Please enter a First Name<br>'; $error2='*Please enter a Last Name<br>'; $error3='*Please enter a Phone Number<br>'; $error4='*Please choose a state<br>'; $error5='*Please enter a valid email address<br>'; $day2 = mktime(0,0,0,date("m"),date("d")+2,date("Y")); $day3 = mktime(0,0,0,date("m"),date("d")+3,date("Y")); $day7 = mktime(0,0,0,date("m"),date("d")+7,date("Y")); if($FirstName=="") {echo $error1; exit;} if($LastName=="") {echo $error2; exit;} if($PhoneNumber=="") {echo $error3; exit;} if($State=="") {echo $error4; exit;} if($EmailAddress=="") {echo $error5; exit;} if($State == "NY") { echo "$FirstName $LastName - we will get back to you within 2 days, ie before " .date("d M Y", $day2); exit; } if($State == "NJ") { echo "$FirstName $LastName - we will get back to you within 3 days, ie before " .date("d M Y", $day3); exit; } if($State == "Other") { echo "$FirstName $LastName - we will get back to you within 1 week, ie before " .date("d M Y", $day7); exit; } The following errors come up: Notice: Undefined index: FirstNameTextBox in C:\Users\Jonny P\Documents\My Web Sites\JMPMySite\AddContact.php on line 14 Notice: Undefined index: LastNameTextBox in C:\Users\Jonny P\Documents\My Web Sites\JMPMySite\AddContact.php on line 15 Notice: Undefined index: PhoneNumberTextBox in C:\Users\Jonny P\Documents\My Web Sites\JMPMySite\AddContact.php on line 16 Notice: Undefined index: EmailAddressTextBox in C:\Users\Jonny P\Documents\My Web Sites\JMPMySite\AddContact.php on line 17 Notice: Undefined index: AddressTextBox in C:\Users\Jonny P\Documents\My Web Sites\JMPMySite\AddContact.php on line 18 Notice: Undefined index: CityTextBox in C:\Users\Jonny P\Documents\My Web Sites\JMPMySite\AddContact.php on line 19 Notice: Undefined index: StateDropDownBox in C:\Users\Jonny P\Documents\My Web Sites\JMPMySite\AddContact.php on line 20 Notice: Undefined index: ZipTextBox in C:\Users\Jonny P\Documents\My Web Sites\JMPMySite\AddContact.php on line 21 *Please enter a First Name Again, ANY help is greatly appreciated.. it is for a class, but I have honestly exhasted all my sources to figure out what is wrong. Are my codes correct and all there? Thanks for the help! -WPN Hello, my first post here. I created a Validation class that depends entirely on static methods. It appears to be working well, but perhaps I misunderstood exactly the purpose and the consequences of using static methods. My class essentially looks like this: class Validate { static public $errors = array(); static public $valid = array(); static public function Name($name) { if ($name != '') { self::$valid['name'] = $name; return true; } else { self::$errors['name'] = 'Name is empty'; return false; } } } Does this create any chance whatsoever for a collision of data from multiple users? I am beginning to think it does, simply because from what I have recently learned about static methods, theyr'e essentially global variables because they are not instantiated. If that's the case, then it would seem possible that during times of heavy use, any application depending on this class would confuse submitted data. Any thoughts? Thanks in advance. Am new here - looks like a great foru! I would sincerely appreciate any help anyone can give me. I have been trying to solve my problem for hours and I am not having any luck, so I thought I would post and see if anyone can help. I am very stuck and am not making much progress on this project, and I am certain the answer is very simple. I am constructing a form to collect data for a specialized purpose. The form and program actually work for its intended function, but I am trying to enhance the user experience by preventing customers from having to reenter all of their data should there be a problem with any of the data submitted. I have been able to do that with the contact form portion, but what I am having trouble with is the portion which has as many as 400 possible entries. So, in a nutshell, if the customers contact data is incomplete or in error, the form will ask them to return to the page and correct things. The previous data entered has been saved in the session and the input value will equal the previous entry. i.e. <tr> <td align="right" class="infoBox"><?php echo ENTRY_EMAIL_ADDRESS; ?></td> <td align=left><?php echo "<input type=text name='cemail' value=\"$cemail\" size=35 maxlength=35>" ?></td> </tr> Works perfectly, all well and good there. On the other 400 more or less entries, I am having a difficult time tweaking the string concatenation to work to achieve similar results. There are 4 columns each with $points entries asking for a dimension in either feet or inches. The <input name=> is one of ptaf,ptai,ptbf,ptbi, appended programatically with the corresponding row number or data point. i.e. "ptaf1", "ptai1", etc... This is produced by the example below and works perfectly also. <?php { $points=100; $i=1; while ($i <= $points) {echo ' <tr><td align="center" width="6"><b> ' .$i . '</b></td> <td align="right" NOWRAP>A' .$i . ' (ft) <input type="text" name="ptaf'.$i.'" size=4 maxlength=3> </td> <td align="right" NOWRAP>A' .$i . ' (in) <input type="text" name="ptai'.$i.'" size=4 maxlength=4> </td> <td align="right" NOWRAP>B' .$i . ' (ft) <input type="text" name="ptbf'.$i.'" size=4 maxlength=3> </td> <td align="right" NOWRAP>B' .$i . ' (in) <input type="text" name="ptbi'.$i.'" size=4 maxlength=4> </td> '; $i++; } } ?> I am trying to add <input value=$ptai.$i> for each field but as I mentioned I am not having any luck. It seems as if I have tried every combination imagineable, but still no luck. My head is spinning! The closest I seem to have gotten was with this: <td align="right" NOWRAP>A' .$i . ' (ft) <input type="text" size=6 maxlength=3 name="ptaf'.$i.'" value="' . "$ptaf" . $i . '" ></td> But line 17 for example returns this: <input type="text" value="17" name="ptaf17" maxlength="3" size="6"> To recap, I am trying to have the value set to whatever the customer may have entered previously. Again, I would most appreciate any help anyone can give me. If you need clarification on anything please let me know. Thanks AJ Say there is a complex opt in process where people start to enter their data but certain questions stop them where they close out of the page. They already entered their data and I feel there is a way to grab it and post it to mysql even though they do not click submit.
How would this be done?
A super simple example (proof of concept) or a link to a tutorial would be very useful.
Edited by brentman, 23 September 2014 - 10:42 AM. Hello, I have coded a contact form in PHP and I want to know, if according to you, it is secure! I am new in PHP, so I want some feedback from you. Moreover, I have also two problems based on the contact form. It is a bit complicated to explain, thus, I will break each of my problem one by one. FIRST:The first thing I want to know, is if my contact form secure according to you: The HTML with the PHP codes: Code: [Select] <?php if ($_SERVER['REQUEST_METHOD'] == 'POST') { //Assigning variables to elements $first = htmlentities($_POST['first']); $last = htmlentities($_POST['last']); $sub = htmlentities($_POST['subject']); $email = htmlentities($_POST['email']); $web = htmlentities($_POST['website']); $heard = htmlentities($_POST['heard']); $comment = htmlentities($_POST['message']); $cap = htmlentities($_POST['captcha']); //Declaring the email address with body content $to = 'alithebestofall2010@gmail.com'; $body ="First name: '$first' \n\n Last name: '$last' \n\n Subject: '$sub' \n\n Email: '$email' \n\n Website: '$web' \n\n Heard from us: '$heard' \n\n Comments: '$comment'"; //Validate the forms if (empty($first) || empty($last) || empty($sub) || empty($email) || empty($comment) || empty($cap)) { echo '<p class="error">Required fields must be filled!</p>'; header ('refresh= 3; url= index.php'); return false; } elseif (filter_var($first, FILTER_VALIDATE_INT) || filter_var($last, FILTER_VALIDATE_INT)) { echo '<p class="error">You cannot enter a number as either the first or last name!</p>'; return false; } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) { echo '<p class="error">Incorrect email address!</p>'; return false; } elseif (!($cap === '12')){ echo '<p class="error">Invalid captcha, try again!</p>'; return false; } else { mail ($to, $sub, $body); echo '<p class="success">Thank you for contacting us!</p>'; } } ?> <form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post"> <p>Your first name: <span class="required">*</span></p> <p><input type="text" name="first" size="40" placeholder="Ex: Paul"/></p> <p>Your last name: <span class="required">*</span></p> <p><input type="text" name="last" size="40" placeholder="Ex: Smith"/></p> <p>Subject: <span class="required">*</span></p> <p><input type="text" name="subject" size="40" placeholder="Ex: Contact"/></p> <p>Your email address: <span class="required">*</span></p> <p><input type="text" name="email" size="40" placeholder="Ex: example@xxx.com"/></p> <p>Website:</p> <p><input type="text" name="website" size="40" placeholder="Ex: http//:google.com"/></p> <p>Where you have heard us?: <span class="required">*</span></p> <p><select name="heard"> <option>Internet</option> <option>Newspapers</option> <option>Friends or relatives</option> <option>Others</option> </select></p> <p>Your message: <span class="required">*</span></p> <p><textarea cols="75" rows="20" name="message"></textarea></p> <p>Are you human? Sum this please: 5 + 7 = ?: <span class="required">*</span></p></p> <p><input type="text" name="captcha" size="10"/></p> <p><input type="submit" name="submit" value="Send" class="button"/> <input type="reset" value="Reset" class="button"/></p> </form> SECOND PROBLEM:If a user has made a mistake, he gets the error message so that he can correct! However, when a mistake in the form occurs, all the data the user has entered are disappeared! I want the data to keep appearing so that the user does not start over again to fill the form. THIRD: When the erro message is displayed to notify the user that he made a mistake when submitting the form, the message is displaying on the top of the page. I want it to appear below each respective field. How to do that? In JQuery it is simple, but in PHP, I am confusing! There are two pieces to this- The HTML Form and the resulting php. I can't seem to make the leap, from the code to having the form produce the php page so others can view it until the form is again submitted overwriting the php, thus generating new content. The environment I am working in is limited to IIs 5.1 and php 5.2.17 without mySQL or other DB I'm new to php, this isn't homework,or commercialization, it's for children. I am thinking perhaps fwrite / fread but can't get my head around it. Code snipets below. Any help, please use portions of this code in hopes I can understand it Thanks Code snipet from Output.php Code: [Select] <?php $t1image = $_POST["t1image"]; $t1title = $_POST["t1title"]; $t1info = $_POST["t1info"]; $t2image = $_POST["t2image"]; $t2title = $_POST["t2title"]; $t2info = $_POST["t2info"]; ?> ... <tbody> <tr><!--Headers--> <td style="vertical-align: top; text-align: center; background-color: rgb(204, 255, 255);">Animal</td> <td style="vertical-align: top; text-align: center; background-color: rgb(204, 255, 255);">Image thumb<br> </td> <td style="vertical-align: top; text-align: center; background-color: rgb(204, 255, 255);">Date<br> </td> <td style="vertical-align: top; text-align: center; background-color: rgb(204, 255, 255);">Information<br> </td> </tr> <tr> <td style="vertical-align: top; text-align: center;">Monkey </td> <td style="vertical-align: top; text-align: center;"><img src="<?php echo $t1image.'.gif'; ?>"><!--single image presented selected from radio buttons--> </td> <td style="vertical-align: top; text-align: center;"><?php echo date("m/d/Yh:i A"); ?><!--time stamp generated when submitted form populates all fields at once--> </td> <td style="vertical-align: top; text-align: center;"><a href="#monkey" rel="facebox"><?php echo $t1title ?></a><!--Link name provided by "Title 1", that links to hidden Div generated page with content from "Info1" field--> <div id="Monkey" style="display:none"> <?php echo $t1info; ?> </div> </td> </tr> <tr> <td style="vertical-align: top; text-align: center;">Cat<br> </td> <td style="vertical-align: top; text-align: center;"><img src="<?php echo $t2image.'.gif'?>"></td> <td style="vertical-align: top; text-align: center;"><?php echo date("m/d/Yh:i A"); ?></td> <td style="vertical-align: top; text-align: center;"><a href="#Cat" rel="facebox"><?php echo $t2title ?></a> <div id="Cat" style="display:none"> <?php echo $t2info; ?> </div> </td> </tr> <tr> This replicates several times down the page around 15-20 times ( t1### - t20###) Code Snipet from HTML Form Code: [Select] <form action="animals.php" method="post"> <div style="text-align: left;"><big style="font-family: Garamond; font-weight: bold; color: rgb(51, 51, 255);"><big><big><span>Monkey</span></big></big></big><br> <table style="text-align: left; width: 110px;" border="0" cellpadding="2" cellspacing="0"> <tbody><tr> <td style="vertical-align: top;">Image thumb<br> <input type="radio" name="t1image" value="No opinion" checked><img src="eh.gif" alt="Eh"> <input type="radio" name="t1image" value="Ok"><img src="ok.gif" alt="ok"> <input type="radio" name="t1image" value="Like"><img src="like.gif" alt="Like"> <input type="radio" name="t1image" value="Dont"><img src="dont.gif" alt="Don't Like"> <input type="radio" name="t1image" value="Hate"><img src="hate.gif" alt="Hate"> <input type="radio" name="t1image" value="Other"><img src="other.gif" alt="Other"> <br> Why Title:<input type="text" name="t1title" size="45" value="..."/></td> <td style="vertical-align: top;"> Explain:<br> <textarea name="t1info" cols=45 rows=3 value="..."></textarea> </td></tr></table> <br> <!--Next--> How do I get the Form data to save to the php page for others to view? How can I go about validating a form in PHP? I am trying to do so, but I am clueless as to how to structure it. Hi all, Im trying to add validation to a form to allow PHP to check before its sends the values to another page for them to be uploaded to a database. The problem i have is that i have taken a, i thought simple PHP validating script off the net and i cant seem to get it to work, its just giving me a blank page. I dont know if the script is outdated, i dont think it is. The script is he Code: [Select] <?php include("validation.php"); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>Test Area</title> <link rel="stylesheet" href="test.css" type="text/css" media="screen" /> </head> <body> <div id="container"> <h1>Add a Product</h1> <?if(isset($_POST['send'])&amp;amp;amp;amp;amp;amp;amp;amp;&amp;amp;amp;amp;amp;amp;amp;amp;(!validateModel($_POST['model']) || !validatePrice($_POST['price']) || !validateDescription($_POST['description']) ) ):?> <div id="error"> <ul> <?if(!validateModel($_POST['model'])):?> <li><strong>Invalid Name:</strong> We want names with more than 3 letters!</li> <?endif?> <?if(!validatePrice($_POST['price'])):?> <li><strong>Invalid E-mail:</strong> Type a Valid Price!</li> <?endif?> <?if(!validateDescription($_POST['description'])):?> <li><strong>Invalid message:</strong> Type a message with at least with 10 letters</li> <?endif?> </ul> </div> <?elseif(isset($_POST['send'])):?> <div id="error" class="valid"> <ul> <li><strong>Congratulations!</strong> All fields are OK ;)</li> </ul> </div> <?endif?> <form method="post" id="customForm" action="" enctype="multipart/form-data"> <div> <label for="model">Model Number</label> <input id="model" name="model" type="text" /> <span id="modelInfo">Please enter your Product Model Number!</span> </div> <div> <label for="product">Product</label> <select class="products" name="products"> <option value="0">Please select an option below</option> <option value="1">19" LCD TV</option> <option value="2">22" LCD TV</option> <option value="3">26" LCD TV</option> <option value="4">32" LCD TV</option> <option value="5">37" LCD TV</option> <option value="6">42" LCD TV</option> <option value="7">37" Plasma TV</option> <option value="8">42" Plasma TV</option> <option value="9">46" Plasma TV</option> <option value="10">50" Plasma TV</option> <option value="11">54" Plasma TV</option> <option value="12">58" Plasma TV</option> <option value="13">Wall Bracket</option> <option value="14">Home Cinema System</option> <option value="15">Bluray Home Cinema System</option> <option value="16">DVD Recorder</option> <option value="17">DVD Player</option> <option value="18">DVD Portable</option> <option value="">Bluray Recorder</option> <option value="">Bluray Player</option> <option value="">Bluray Portable</option> <option value="">Projector</option> <option value="">37" LCD TV</option> <option value="">42" LCD TV</option> <option value="">Personal Video Recorder (PVR)</option> <option value="">3D Technology</option> <option value="">Upright Cleaner</option> <option value="">Cylinder Cleaner</option> <option value="">DECT Phone</option> <option value="">DECT Answer Phone</option> <option value="">Washing Machines</option> <option value="">Tumble Dryers</option> <option value="">Dishwashers</option> <option value="">Fridge-Freezers</option> <option value="">Freezers</option> <option value="">Refridgerators</option> <option value="">Microwave (Solo)</option> <option value="">Microwave (Grill)</option> <option value="">Microwave Combination</option> <option value="">Kettles</option> <option value="">Toasters</option> <option value="">Irons</option> <option value="">Breadmakers</option> <option value="">Microsystems</option> <option value="">Minisystems</option> <option value="">CD, Radio and Cassette Players</option> <option value="">Pure Radios</option> <option value="">Dimplex Fires</option> <option value="">Convector Heaters</option> <option value="">Fan Heaters</option> <option value="">Mens Shavers/Grooming</option> <option value="">Ladies Shavers/Beauty</option> <option value="">Straighteners</option> <option value="">Epilators</option> <option value="">Stylish Cameras</option> <option value="">Super Zoom Cameras</option> <option value="">SD Camcorders</option> <option value="">HD Camcorders</option> <option value="">HDD Camcorders</option> <option value="">Bluray Discs</option> <option value="">DVD Discs</option> <option value="">Leads</option> <option value="">Mini DV Tapes</option> <option value="">SD/SDHC/SDXC Cards</option> </select> <span id="productInfo">Please choose a Product Title!</span> </div> <div> <label for="price">Price</label> <input id="price" name="price" type="text" /> <span id="priceInfo">Please enter a Price!</span> </div> <div> <label for="photo">Image</label> <input style="font-size:13px;" class="file" name="photo" type="file" /> <span id="photoInfo">Please choose an Image!</span> </div> <div> <label for="message">Description</label> <textarea id="description" name="description" cols="" rows=""></textarea> </div> <div> <input id="send" name="send" type="submit" value="Send" /> </div> </form> </div> </body> </html> This is the validation file: <?php function validateModel($model){ //if it's NOT valid if(strlen($model) < 4) return false; //if it's valid else return true; } function validatePrice($price){ //if it's NOT valid if(strlen($price) < 4) return false; //if it's valid else return true; } function validateDescription($description){ //if it's NOT valid if(strlen($description) < 10) return false; //if it's valid else return true; } ?> I can't spot the problem, any suggestions? Hi, I am trying to setup a PHP script that will validate an html form. The form and the PHP script are separate from each other. The code that I have was modified from a tutorial on YouTube. The example used there works but as I have began to tailor it to my purpose, it is now broke. I just added one line for validation to simplify troubleshooting. If I find an empty field on the form, I would like to display the error message on the form itself rather than start a new html page with the PHP script. I am not sure if that is possible. Here is my form: http://www.tallfirshoa.com/adform.htm YouTube videos that I was working from. The video's example has the form and PHP combined as one. In my case, I need the form and PHP separate. http://www.youtube.com/watch?v=yuLpSospbBk&feature=search http://www.youtube.com/watch?v=LF5zTWthpn0&feature=search The code works fine if I leave out the validation. As soon as I add if(!$fname), the script becomes broken. I'm guessing that it has something to do with $errorstring and how it works. I am new to PHP and have tried as many things as I can think of but I can't make any forward progress. Thanks for your help! Rob Code: [Select] <html> <h1>Tall Firs Ad Submission</h1> <?php if ($_POST['submit']) { //Get form data $fname = $_POST['fname']; $lname = $_POST['lname']; $email = $_POST['email']; $displayemail = $_POST['displayemail']; $phone = $_POST['phone']; $category = $_POST['category']; $description = $_POST['description']; //Declare variables $to = "email@gmail.com"; $subject = "Request"; $headers = "From: $email \r\n Reply-To: $email"; } //Setup form validation $errorstring = "" //default value of error string //Begin validation if (!$fname) $errorstring = $errorstring."First Name<br>"; ?> </html> Hi all! Im trying to modify a script so that when a user submits data on a form if there are any errors it flags all errors and not just the first one the script comes to and 'dies'. Heres the form code <?php session_start(); ?> <!--//-----------------------------------------------------------------------------------------------+ | // Sample AJAX web form By: Codex-m | // http://www.php-developer.org | // You are free to use and improve this script provided you link to author web site: http://www.php-developer.org | //--------------------------------------------------------------------------------------------------------------> <html> <head> <title>Sample AJAX Web Form</title> <script type="text/javascript" src="prototype.js"></script> <script type="text/javascript"> function sendRequest() { new Ajax.Request("ajaxvalidate.php", { method: 'post', parameters: 'name='+$F('name')+'&phonenumber='+$F('phonenumber')+'&age='+$F('age')+'&captcha='+$F('captcha'), onComplete: showResponse }); } function showResponse(req){ $('show').innerHTML= req.responseText; } </script> <style type="text/css"> P.yellow {background-color: #ffff00;} </style> </head> <body> <h3>This is a sample PHP web form with AJAX validation</h3> Please complete the form below and then press "Submit button".<br /> <br /><br /> <form action="/ajaxwebform/ajaxvalidate.php" method="post" onsubmit="return false;"> Enter your Full Name, First name and Last name ONLY (Example: John Doe)<br /> <input style="background-color: #FFFFC0" type="text" name="name" id="name" size="50"> <br /><br /> Enter your Phone number (numbers only, no dashes and spaces)<br /> <input style="background-color: #FFFFC0" type="text" name="phonenumber" id="phonenumber" size="35"> <br /><br /> Enter your Age (Numbers only)<br /> <input style="background-color: #FFFFC0" type="text" name="age" id="age" size="50"> <br /><br /> <img src="/ajaxwebform/captcha.php" /> <br /> Enter the Captcha as shown above: <br /> <br /> <input style="background-color: #FFFFC0" type="text" name="captcha" id="captcha" size="10"> <br /> <br /> <input type="submit" value="Submit" onClick="sendRequest()"> </form> <br /> This form will validate your data entry using AJAX. If you are correct with your data entry, the entire information entered will be shown in this page without reloading. <br /> <br /><br /> <p class="yellow" id="show"></p> </body> </html> Heres the php validating code <?php session_start(); ?> <!--//-----------------------------------------------------------------------------------------------+ | // Sample AJAX web form By: Codex-m | // http://www.php-developer.org | // You are free to use and improve this script provided you link to author web site: http://www.php-developer.org | //--------------------------------------------------------------------------------------------------------------> <?php //start session to recover captcha answers //connect to database $username = "root"; $password = ""; $hostname = "localhost"; $database = "newdb"; $dbhandle = mysql_connect($hostname, $username, $password) or die("Unable to connect to MySQL"); $selected = mysql_select_db($database,$dbhandle) or die("Could not select $database"); //extract form inputs $name =$_POST['name']; $phonenumber =$_POST['phonenumber']; $age =$_POST['age']; $usercaptchaanswer =$_POST['captcha']; $correctcaptcha = $_SESSION['answer']; //sanitize early for any possible MySQL entry $name = mysql_real_escape_string(stripslashes(trim($name))); $phonenumber = mysql_real_escape_string(stripslashes(trim($phonenumber))); $age = mysql_real_escape_string(stripslashes(trim($age))); $usercaptchaanswer = mysql_real_escape_string(stripslashes(trim($usercaptchaanswer))); $correctcaptcha = mysql_real_escape_string(stripslashes(trim($correctcaptcha))); Validate captcha entry if ($correctcaptcha != $usercaptchaanswer) { echo 'ERROR: You have entered wrong captcha code'; die (); } //Step 2 of data validation: check for blank entries if (empty($name)) { //name field is blank echo 'ERROR: The name field is empty.'; die (); } if (empty($phonenumber)) { //phone field is blank echo 'ERROR: The phone field is empty.'; die (); } if (empty($age)) { //age field is blank echo 'ERROR: The age field is empty.'; die (); } if (empty($usercaptchaanswer)) { captcha field is blank echo 'ERROR: The captcha field is empty.'; die (); } //Step 3 of data validation: Ensuring correct format //Step 3.1 validate full name, presence of first name and last name $mystring = $name; $findme = ' '; $pos = strpos($mystring, $findme); $actualposition =$pos + 1; //count strings $count =strlen($mystring); //count the number of characters for the first name $countfirstname = $actualposition - 1; //count the number of characters for the last name $countlastname = $count - $actualposition; //detect if full name has middle name $posmid= strpos($mystring,$findme,$actualposition) + 1; $middleadjust = $posmid - $actualposition; $purealpha = str_replace(" ", "x", $mystring); if ($actualposition==1) { echo 'ERROR: You either forgot your first name or your last name.'; die (); } if ($countfirstname <2) { echo 'ERROR: You are using an invalid first name, it should contain more than one character.'; die (); } if ($countlastname <2) { echo 'ERROR: You are using an invalid last name, it should contain more than one character.'; die (); } if ($middleadjust >= 2) { echo 'ERROR: You should not be using a middle name, please use only first name and last name.'; die (); } if (!(ctype_alpha($purealpha))) { echo 'ERROR: Full name can only consist of alphabetic characters.'; die (); } //Step 3.2 Validate phone number if (!(ctype_digit($phonenumber))) { echo 'ERROR: A phone number should consist of numerical digits only and no spaces between numbers'; die (); } //Step 3.3 Validate age if (!(ctype_digit($age))) { echo 'ERROR: Your age should consist of numerical digits only and no spaces between numbers'; die (); } //Step 4. If all data entry is correct, show results in another page, assigned all values to sessions echo 'Thank you for the correct data entry, below are the information entered:'; echo '<br />'; echo 'Your full name is: '.$name; echo '<br />'; echo 'Your phone number is: '.$phonenumber; echo '<br />'; echo 'Your age is: '.$age; echo '<br />'; echo '<a href="/ajaxwebform/ajaxwebformtest.php">Click here to enter another data.</a>'; $_SESSION = array (); session_destroy (); mysql_close($dbhandle); ?> Hi I am currently writing code to validate a form using PHP. What i wanted was to validate all inputs and then post the data to a external mysql server. However, i want a function placed on the submit/send button of the form, in which the function checks to see if there are no errors and then forwards the user to another page where the data is inserted into the sql database. Here is what i have so far: add_test.php Code: [Select] <?php include("validation.php"); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>test</title> <link rel="stylesheet" href="test.css" type="text/css" media="screen" /> </head> <body> <div id="container"> <h1>Add a Product</h1> <?php if(isset($_POST['send']) AND (!validateModel($_POST['model']) || !validatePrice($_POST['price']) || !validateProduct($_POST['product']) || !validateImage($_FILES['photo']) || !validateDescription($_POST['description']) ) ):?> <div id="error"> <ol> <center><p><b>Oops, Please fix these errors:</b></p></center><br /> <?php if(!validateModel($_POST['model'])):?> <li><strong>Invalid Model:</strong> Model Number must be more than 3 letters!</li> <?php endif?> <?php if(!validatePrice($_POST['price'])):?> <li><strong>Invalid Price:</strong> Price must be in integers!</li> <?php endif?> <?php if(!validateProduct($_POST['product'])):?> <li><strong>Invalid Product:</strong> You didn't select a product!</li> <?php endif?> <?php if(!validateImage($_FILES['photo'])):?> <li><strong>Invalid Image:</strong> You didn't select an image! - (ONLY: GIF/JPEG/JPG/PNG)</li> <?php endif?> <?php if(!validateDescription($_POST['description'])):?> <li><strong>Invalid Description:</strong> Description must have at least 10 characters in length!</li> <?php endif?> </ol> </div> <?elseif(isset($_POST['send'])):?> <div id="error" class="valid"> <ul> <li><strong>Congratulations!</strong> All fields are OK ;)</li> </ul> </div> <?endif?> <form method="post" id="customForm" action="" enctype="multipart/form-data"> <div> <label for="model">Model Number</label> <input id="model" name="model" type="text" /> <span id="modelInfo">Please enter your Product Model Number!</span> </div> <div> <label for="product">Product</label> <select class="product" name="product"> <option value="please_select">Please select an option below</option> <option value="1">19" LCD TV</option> <option value="2">22" LCD TV</option> <option value="3">26" LCD TV</option> <option value="4">32" LCD TV</option> <option value="5">37" LCD TV</option> <option value="6">42" LCD TV</option> <option value="7">37" Plasma TV</option> <option value="8">42" Plasma TV</option> <option value="9">46" Plasma TV</option> <option value="10">50" Plasma TV</option> <option value="11">54" Plasma TV</option> <option value="12">58" Plasma TV</option> <option value="13">Wall Bracket</option> <option value="14">Home Cinema System</option> <option value="15">Bluray Home Cinema System</option> <option value="16">DVD Recorder</option> <option value="17">DVD Player</option> <option value="18">DVD Portable</option> <option value="">Bluray Recorder</option> <option value="">Bluray Player</option> <option value="">Bluray Portable</option> <option value="">Projector</option> <option value="">37" LCD TV</option> <option value="">42" LCD TV</option> <option value="">Personal Video Recorder (PVR)</option> <option value="">3D Technology</option> <option value="">Upright Cleaner</option> <option value="">Cylinder Cleaner</option> <option value="">DECT Phone</option> <option value="">DECT Answer Phone</option> <option value="">Washing Machines</option> <option value="">Tumble Dryers</option> <option value="">Dishwashers</option> <option value="">Fridge-Freezers</option> <option value="">Freezers</option> <option value="">Refridgerators</option> <option value="">Microwave (Solo)</option> <option value="">Microwave (Grill)</option> <option value="">Microwave Combination</option> <option value="">Kettles</option> <option value="">Toasters</option> <option value="">Irons</option> <option value="">Breadmakers</option> <option value="">Microsystems</option> <option value="">Minisystems</option> <option value="">CD, Radio and Cassette Players</option> <option value="">Pure Radios</option> <option value="">Dimplex Fires</option> <option value="">Convector Heaters</option> <option value="">Fan Heaters</option> <option value="">Mens Shavers/Grooming</option> <option value="">Ladies Shavers/Beauty</option> <option value="">Straighteners</option> <option value="">Epilators</option> <option value="">Stylish Cameras</option> <option value="">Super Zoom Cameras</option> <option value="">SD Camcorders</option> <option value="">HD Camcorders</option> <option value="">HDD Camcorders</option> <option value="">Bluray Discs</option> <option value="">DVD Discs</option> <option value="">Leads</option> <option value="">Mini DV Tapes</option> <option value="">SD/SDHC/SDXC Cards</option> </select> <span id="productInfo">Please choose a Product Title!</span> </div> <div> <label for="price">Price</label> <input id="price" name="price" type="text" /> <span id="priceInfo">Please enter a Price!</span> </div> <div> <label for="photo">Image</label> <input style="font-size:13px;" class="file" name="photo" type="file" /> <span id="imageInfo">Please choose an Image!</span> </div> <div> <label for="message">Description</label> <textarea id="description" name="description" cols="" rows=""></textarea> </div> <div> <input id="send" name="send" type="submit" value="Send" /> </div> </form> </div> </body> </html> Here is my validation php document validation.php <?php function validateModel($model){ //if it's NOT valid if(strlen($model) < 4) return false; //if it's valid else return true; } function validatePrice($price){ //if it's NOT valid if(is_numeric($price) == '') return false; //if it's valid else return true; } function validateProduct($product){ //if it's NOT valid if(($product)=='please_select') return false; //if it's valid else return true; } function validateImage($photo){ //if it's valid if ((($_FILES["photo"]["type"] == "image/gif") || ($_FILES["photo"]["type"] == "image/jpeg") || ($_FILES["photo"]["type"] == "image/pjpeg")) && ($_FILES["photo"]["size"] < 2000000)) return true; else return false; } function validateDescription($description){ //if it's NOT valid if(strlen($description) < 10) return false; //if it's valid else return true; } ?> any suggestions on how to write the code for the send button? Im abit stuck and being a newbie dont help lol. Hello All, I am a newbie to PHP and I'm working on a marathon sign up form for my final project and could really use the help. The trouble i'm having is sending and retrieving database from the database. Below is the code i am using. Can someone please review and tell me where I went wrong.
(This is the code that is sitting at the top of my document)
<?php
}
(This is my form [submit_registration] )
<div class="contact"> Hi there, I've got a HTML textarea with the name attribute of 'review' and I've posted this into a variable called $review. I want to say if the characters are less than 30, please enter more words etc. The problem is, I get the if statement's error even when there are more than 30 characters. Can anyone figure out why I'm getting this? Code: [Select] if ($review < 30){ echo '<p class="red">Review is too short, please enter at least 15 words</p>'; } I have a pretty complicated script i'm trying to work on but i'm not having much luck. Basically what needs to happen is i need part of my script to check a database and count 2 different sets of data for the current date, then if both conditions are true then submit the users name, current date, and a time id to the database it checks, and then submit the form data to a text file. i'll try and map it out. check database for how many times the username appears for current date if it is less than 3 move to next validation if it is false, give error message check database for how many times the time id appears for current date if it is less than 30 move to next section if it is false, give error message send username, timestamp (of clients computer), and time id to the 'totals' database and send form data to text file. So.... thats it in a nutshell. I'm going to have to go into my 'cart' page and edit in a row to have the order#, username, timestamp, and time id before the rest of the order details Hi. I'm new to PHP and have a problem with some form validation. The code below is my contact form. It was working until I added a dropdown list and checkbox. For all the other fields I created an input variable using the 'name' attribute to reference the data entered into the input fields and the validation appeared to work and an email was sent to the appropriate email address. For the checkbox field I have also created a 'name' attribute but don't know whether this is right way to confirm whether the box has been checked? For the field with a dropdown selection I have used the option 'selected', but again, don't know whether this is right or not. Now when I enter valid data into all the fields, select a value from the dropdown and check the checkbox, I get an error message stating that I need to fill in all the form fields. I am pretty sure it is to do with the way I have tried to pick up the data from dropdown list and the checkbox, but can't figure out what it is. Any help would be much appreciated. Thanks in advance.
<?php echo file_get_contents('header.php'); ?> <?php // Message Vars $msg = ''; $msgClass = ''; // Check to see if the form has been submitted if(filter_has_var(INPUT_POST, 'submit')) { //Input Data Variables $firstname = htmlspecialchars($_POST['firstname']); $lastname = htmlspecialchars($_POST['lastname']); $phonenumber = htmlspecialchars($_POST['phonenumber']); $email = htmlspecialchars($_POST['email']); $selected = htmlspecialchars($_POST['selected']); $message = htmlspecialchars($_POST['message']); $checkbox = htmlspecialchars($_POST['checkbox']); //Check required fields if(!empty($firstname) && !empty($lastname) && !empty($phonenumber) && !empty($email) && !empty($selected) && !empty($message) && !empty($checkbox)) { // If passed, check email address if(filter_var($email, FILTER_VALIDATE_EMAIL) === false) { //If failed, Email address is not valid $msg = 'Please use a valid email address'; $msgClass = 'alert-danger'; } else { //Recipient email address and information to be sent to them $toEmail = 'hello@example.co.uk'; $subject = 'Contact Request from Website'; $body = '<h2>Contact Request</h2> <h4>Name</h4><p>'.$firstname. ''.$lastname.'</p> <h4>Phone Number</h4><p>'.$phonenumber.'</p> <h4>Email Address</h4><p>'.$email.'</p> <h4>Subject</h4><p>'.$selected.'</p> '; // Email Headers $headers = "MIME-VERSION: 1.0" ."\r\n"; $headers .="Content-Type:text/html;charset=UTF-8" ."\r\n"; // Additional Headers $headers .= "From: " .$firstname. " ".$lastname." <".$email.">" ."\r\n"; if(mail($toEmail, $subject, $body, $headers)) { // Message Sent $msg = 'Your message has been sent'; $msgClass = 'alert-success'; } else { // Message failed $msg = 'Your message has NOT been sent'; $msgClass = 'alert-danger'; } } } else { //Failed $msg = 'Please fill in all fields'; $msgClass = 'alert-danger'; } } ?> <div class="container clearfix content-container"> <h1 class="section-title">Contact Us</h1> <p>If you have any questions about the services we provide or would like to chat about a new website project, please get in touch using any of the options below. We would love to hear from you!</p> <!--Contact Page Row--> <div class="row"> <div class="col-lg-6 contact-details"> <div class="row"> <div class="col-lg-12"> <img src="assets/img/contact-us.jpg" class="img-responsive d-block contact-image" alt="Contact Us Image"> </div> </div> <div class="row"> <div class="col-lg-12 contact-name"> <span class="d-inline-block contact-inline-block"><i class="fas fa-user fa-2x"> </i></span> <span class="d-inline-block"><p class="contact-details">sn0wman23</p></span> </div> </div> <div class="row"> <div class="col-lg-12 contact-phone"> <span class="d-inline-block contact-inline-block"><a href="tel:+447740484798"><i class="fas fa-mobile-alt fa-2x"></i></a></span> <span class="d-inline-block"><a href="tel:+441234567890"><p class="contact-details">01234 567890</a></p></span> </div> </div> <div class="row"> <div class="col-lg-12 contact-email"> <span class="d-inline-block contact-inline-block"><a href="mailto:hello@example.co.uk"><i class="fas fa-envelope-square fa-2x"></i></a></span> <span class="d-inline-block"><a href="mailto:hello@example.co.uk"><p class="contact-details">hello@example.co.uk</a></p></span> </div> </div> <div class="row"> <div class="col-lg-12 contact-fb"> <span class="d-inline-block contact-inline-block"><a href="https://www.facebook.com/" target="_blank"><i class="fab fa-facebook-square fa-2x"></a></i></span> <span class="d-inline-block"><a href="https://www.facebook.com/example/" target="_blank"><p class="contact-details">@example</a></p></span> </div> </div> </div> <!--Contact Form--> <div class="col-lg-6 contact-form d-block"> <?php if($msg != ''): ?> <div class="alert <?php echo $msgClass; ?>"><?php echo $msg; ?></div> <?php endif;?> <form method="post" action="contact.php" role="form"> <div class=" row form-group"> <div class="col-lg-6"> <label for="firstnameid">First name:</label> <input type="text" name="firstname" class="form-control mb-3" id="firstnameid"> </div> <div class="col-lg-6"> <label for="lastnameid">Last name:</label> <input type="text" name="lastname" class="form-control mb-3" id="lastnameid"> </div> </div> <div class="row form-group"> <div class="col-lg-6"> <label for="phonenumber">Phone number:</label> <input type="tel" name="phonenumber" class="form-control mb-3" id="phonenumberid"> </div> <div class="col-lg-6"> <label for="emailid">Email address:</label> <input type="email" name="email" class="form-control mb-3" id="emailid"> </div> </div> <div class="row form-group"> <div class="col-lg-12"> <label for="subjectid">How can I help?:</label> <select class="form-control mb-3" id="subjectid"> <option selected>Select one from this list</option> <option value="1">Value 1</option> <option value="2">Value 2</option> <option value="3">Value 3</option> </select> </div> </div> <div class="row form-group"> <div class="col-lg-12"> <label for="messageid">Tell me a little bit mo </label> <textarea name="message" class="form-control mb-3" id="messageid" rows="6"></textarea> </div> </div> <div class="row form-group"> <div class="col-lg-12 form-check"> <input type="checkbox" name="checkbox" class="form-check-input" id="formcheckid"> <label for="formcheckid" class=form-check-label mb-3>By checking this tickbox you have confirmed that we can collect the information in this form for the purposes outlined in our <a href="privacy-policy.html">privacy policy.</a></label> </div> </div> <div class="row form-group"> <div class="col-lg-12"> <button type="submit" name="submit" class="btn btn-primary mt-4">Send Message </button> </div> </div> </form> </div> <!--Contact Form End--> </div> <!--Contact Page Row End--> </div> <!--Container end--> <?php echo file_get_contents('footer.php'); ?>
I want in my form to validate on the fly(when the user enters the user name) to validate if the user name exists or not. How am i supposed to check if the field name is the same or not with a name in the database.Should i use ajax or javascript? is there any simple example on how to do that. hi, i want to check in a form if a date submitted is not null, how can i modify this script if( empty($_POST['year'] . '-' . $_POST['month'] . '-' .$_POST['day']) |