PHP - Help With Validation
Hi there,
I am working on getting my php form validation working. I just learned why mine wasn't working and it was because I had a header(location) in the middle of the html doc. The reason I had it there was because the code I am using is placed where I want the error to show. Here is the code I am using for this part. I only have one field being validated at the moment. Code: [Select] <? session_start(); if ($_POST['submit']) { $_SESSION['City'] = $_POST['City']; $errors = ""; if(!$_SESSION['City']){ $errors = $errors . "Please enter your city<br>"; } if ($errors != "") { echo "Please check the following errors:<br>"; echo $errors; } else { header("Location: nextpage.php"); } } ?> My question is: What way would you reorganize this (scrapy) validation to where I can redirect my user to a new page when there is no error value? The form page submits to itself with POST. Thanks for your help. Similar TutorialsHello I have a textbox and a input button which will insert a mysql record, however i need to validate that textbox if its empty it shouldnt allow that button to insert any record but show a popup error. my script : <script Language="JavaScript"> function Blank_TextField_Validator() { // Check the value of the element named text_name // from the form named text_form if (frmContact.id.value == "") { // If null display and alert box alert("Please fill in the text field."); // Place the cursor on the field for revision frmContact.id.focus(); // return false to stop further processing return (false); } // If text_name is not null continue processing return (true); } </script>Form : <form name="frmContact" id="frmContact" method="POST" action="index.php" onsubmit="return Blank_TextField_Validator()">however its not validating or showing any error. any help? Edited by sam20e, 11 November 2014 - 10:31 AM. So Im in the weird place where my age validation is not working, any ideas: $dob = strtotime($_POST['dob']); //855993600 Feb 15th 1997 $age_req = strtotime('-13 year', $dob); //445680000 Feb 15th 1984 $time = time(); //1292007621 if ($time < $age_req){} i am using the following to validate a submission form. when i take this validation script out, the php script works fine, however when i use it it redirects to index.html as if their was an error.... please can somebody help, ive tried and cannot see the problem? $fname = $_POST['firstname']; $lname = $_POST['lastname']; $add1 = $_POST['add1']; $add2 = $_POST['add2']; $city = $_POST['city']; $county = $_POST['county']; $country = $_POST['country']; $postcode = $_POST['postcode']; $email1 = $_POST['email1']; $email2 = $_POST['email2']; $mobile = $_POST['mobile']; $home = $_POST['home']; $time = $_POST['time']; $answer = $_POST['answer']; $job = $_POST['job']; $ip = $_SERVER['REMOTE_ADDR']; // validation $validationOK=true; if (Trim($fname)=="") $validationOK=false; if (Trim($lname)=="") $validationOK=false; if (Trim($add1)=="") $validationOK=false; if (Trim($city)=="") $validationOK=false; if (Trim($county)=="") $validationOK=false; if (Trim($country)=="") $validationOK=false; if (Trim($postcode)=="") $validationOK=false; if (Trim($email1)=="") $validationOK=false; if (Trim($email2)!=="$email1") $validationOK=false; if (Trim($mobile)=="") $validationOK=false; if (Trim($time)=="") $validationOK=false; if (Trim($answer)!=="34") $validationOK=false; if (Trim($job)=="") $validationOK=false; if (!$validationOK) { print "<meta http-equiv=\"refresh\" content=\"0;URL=index.html\">"; exit; } Chaps, as a beginner developing his first web app in PHP, I have done fairly well.
However, I am struggling when it comes to validation.
I have written different ELSEIF statements as seen below which would actually carry out the validation itself.
// First name must be filled and in correct format. if(empty($FirstName)) { $errFirstName = '<p class="errText"> Please enter a value</p>'; echo $errFirstName; }elseif(!preg_match('/^[a-z]+$/i',$FirstName)){ $errFirstName = '<p class="errText">Name may not start with a dash. Letters, spaces and dashes are accepted.</p>'; echo $errFirstName; }The problem is that I do not know how to make them "pop up" when the user makes a mistake. I have a form in addteam.php seen below: <form action="pushteam.php" method="post"> <p>Team name: <input type="text" name="TeamName" /></p> <p>Description: </p> <p><textarea name="Description" rows="4" cols="50">Add your description here.</textarea></p> <p><input type="submit"/></p> </form>And a pushplayer.php script that pushes it to a mysql database: // Get values from form $TeamName=$_POST['TeamName']; $Description=$_POST['Description']; } // Insert data into database $sql="INSERT INTO Teams(TeamName, Description)VALUES('$TeamName', '$Description')"; $result=mysql_query($sql); //If successful return to success.php else print error if($result){ header( 'Location: success.php'); } else { header( 'Location: failure.php'); }The scripts function properly. I would really appreciate if someone could guide me in the right direction here. Make the error pop up and make sure the data is not input. At the moment, if I add my ELSEIF statements, it will carry on and insert the data anyway and redirect me. Thanks I'm looking for a bit of help introducing some validation into my "contact us" page. I'm looking to make the user have to enter an email address into textbox And something into the Enquiry box. My 2 files are below: contact-us.shtml Code: [Select] <!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>Byrne Computing Services</title> <link href="styles.css" rel="stylesheet" type="text/css" /> <script src="SpryAssets/SpryMenuBar.js" type="text/javascript"></script> <link href="SpryAssets/SpryMenuBarHorizontal.css" rel="stylesheet" type="text/css" /> <script type="text/javascript" src="inc/jquery.js"></script> <script type="text/javascript" src="inc/easySlider.js"></script> <script type="text/javascript"> $(document).ready(function(){ $("#slider").easySlider(); }); </script> </head> <body> <div id="wrapper"> <!--#include file="inc_header.html" --> <!--#include file="inc_scrollingimages.html" --> <div id="boxesholder"> <!--#include file="inc_specials.html" --> <div id="main"> <div id="mainheader"> Contact Us</div> <div id="maincontent2"> <h2>Fill in the form below and we will contact you shortly.</h2> <p><img src="images/binarycode.jpg" alt="Binary Code" width="167" height="600" class="images" /><form id="form1" name="form1" method="post" action="mailer.php?mail=1"> <strong>Name: </strong><br /> <input name="name" type="text" class="formsingle" id="name" /> <br /> <br /> <strong>Email:</strong><br /> <input name="email" type="text" class="formsingle" id="emailaddress" /> <br /> <br /> <strong>Interested in:</strong><br /> <table border="0" cellspacing="0" cellpadding="0" class="table"> <tr> <td class="interestedin"><strong>Computer Repair</strong></td> <td class="interestedin"><strong>Console Repair</strong></td> <td class="interestedin"><strong>Other Services</strong></td> </tr> <tr> <td class="interestedin"> <input name="virusandmalwareremoval" type="checkbox" class="formcheckbox" id="virusandmalwareremoval" value="virusandmalwareremoval" /> <label for="virusandmalwareremoval">Virus and Malware Removal</label> </td> <td class="interestedin"> <input name="xbox360drivereplacement" type="checkbox" class="formcheckbox" id="xbox360drivereplacement" value="xbox360drivereplacement" /> <label for="ps3drivereplacement">Xbox 360 Drive Replacement</label> </td> <td class="interestedin"> <input name="databackup" type="checkbox" class="formcheckbox" id="databackup" value="databackup" /> <label for="databackup">Data Backup</label> </td> </tr> <tr> <td class="interestedin"> <input name="fullservice" type="checkbox" class="formcheckbox" id="fullservice" value="fullservice" /> <label for="fullservice">Full Service</label> </td> <td class="interestedin"> <input name="xbox360laserreplacement" type="checkbox" class="formcheckbox" id="xbox360laserreplacement" value="xbox360laserreplacement" /> <label for="ps3laserreplacement">Xbox 360 Laser Replacement</label> </td> <td class="interestedin"> <input name="websites" type="checkbox" class="formcheckbox" id="websites" value="websites" /> <label for="websites">Web Design</label> </td> </tr> <tr> <td class="interestedin"> <input name="quickfix" type="checkbox" class="formcheckbox" id="quickfix" value="quickfix" /> <label for="quickfix">Quick Fix</label> </td> <td class="interestedin"> <input name="xbox360rrodrepair" type="checkbox" class="formcheckbox" id="xbox360rrodrepair" value="xbox360rrodrepair" /> <label for="ps3ylodrepair">Xbox 360 RROD Repair</label> </td> <td class="interestedin"> <input name="datarecovery" type="checkbox" class="formcheckbox" id="datarecovery" value="datarecovery" /> <label for="datarecovery">Data Recovery</label> </td> </tr> <tr> <td class="interestedin"> <input name="upgrades" type="checkbox" class="formcheckbox" id="upgrades" value="upgrades" /> <label for="upgrades">Upgrades</label> </td> <td class="interestedin"><input name="ps3drivereplacement" type="checkbox" class="formcheckbox" id="ps3drivereplacement" value="ps3drivereplacement" /> <label for="ps3drivereplacement">PS3 Drive Replacement</label></td> <td class="interestedin"> <input name="networkinstallation" type="checkbox" class="formcheckbox" id="networkinstallation" value="networkinstallation" /> <label for="networkinstallation">Network Installation</label> </td> </tr> <tr> <td> </td> <td class="interestedin"><input name="ps3laserreplacement" type="checkbox" class="formcheckbox" id="ps3laserreplacement" value="ps3laserreplacement" /> PS3 <label for="ps3laserreplacement"> Laser Replacement</label></td> <td class="interestedin"> <input name="mobilephoneissues" type="checkbox" class="formcheckbox" id="mobilephoneissues" value="mobilephoneissues" /> <label for="mobilephoneissues">Mobile Phone Issues</label> </td> </tr> <tr> <td> </td> <td class="interestedin"><input name="ps3ylodrepair" type="checkbox" class="formcheckbox" id="ps3ylodrepair" value="ps3ylodrepair" /> <label for="ps3ylodrepair">PS3 YLOD Repair</label></td> <td class="interestedin"> <input name="emailconfiguration" type="checkbox" class="formcheckbox" id="emailconfiguration" value="emailconfiguration" /> <label for="emailconfiguration">Email Configuration</label></td> </tr> </table> <br /> <strong>Enquiry: </strong><br /> <textarea name="enquiry" class="formmulti" id="enquiry"></textarea> <br /> <br /> <input type="submit" name="button" id="button" value="Submit" /> </form> </p> <p><br /> </p> </div> </div> </div> <!--#include file="inc_offers.html" --> <!--#include file="inc_footer.html" --> </body> </html> Mailer.php Code: [Select] <?php function curPageURL() { $pageURL = 'http'; if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";} $pageURL .= "://"; if ($_SERVER["SERVER_PORT"] != "80") { $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"]; } else { $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"]; } return $pageURL; } if (isset($_REQUEST['name'])) { $name = $_REQUEST['name'] ; $email = $_REQUEST['email'] ; $enquiry = $_REQUEST['enquiry'] ; if (isset($_REQUEST['virusandmalwareremoval'])){ $virusandmalwareremoval = $_REQUEST['virusandmalwareremoval'] . "\n"; } else { $virusandmalwareremoval = ""; } if (isset($_REQUEST['fullservice'])){ $fullservice = $_REQUEST['fullservice'] . "\n"; } else { $fullservice = ""; } if (isset($_REQUEST['quickfix'])){ $quickfix = $_REQUEST['quickfix'] . "\n"; } else { $quickfix = ""; } if (isset($_REQUEST['upgrades'])){ $upgrades = $_REQUEST['upgrades'] . "\n"; } else { $upgrades = ""; } if (isset($_REQUEST['xbox360drivereplacement'])){ $xbox360drivereplacement = $_REQUEST['xbox360drivereplacement'] . "\n"; } else { $xbox360drivereplacement = ""; } if (isset($_REQUEST['xbox360laserreplacement'])){ $xbox360laserreplacement = $_REQUEST['xbox360laserreplacement'] . "\n"; } else { $xbox360laserreplacement = ""; } if (isset($_REQUEST['xbox360rrodrepair'])){ $xbox360rrodrepair = $_REQUEST['xbox360rrodrepair'] . "\n"; } else { $xbox360rrodrepair = ""; } if (isset($_REQUEST['ps3drivereplacement'])){ $ps3drivereplacement = $_REQUEST['ps3drivereplacement'] . "\n"; } else { $ps3drivereplacement = ""; } if (isset($_REQUEST['ps3laserreplacement'])){ $ps3laserreplacement = $_REQUEST['ps3laserreplacement'] . "\n"; } else { $ps3laserreplacement = ""; } if (isset($_REQUEST['ps3ylodrepair'])){ $ps3ylodrepair = $_REQUEST['ps3ylodrepair'] . "\n"; } else { $ps3ylodrepair = ""; } if (isset($_REQUEST['databackup'])){ $databackup = $_REQUEST['databackup'] . "\n"; } else { $databackup = ""; } if (isset($_REQUEST['websites'])){ $websites = $_REQUEST['websites'] . "\n"; } else { $websites = ""; } if (isset($_REQUEST['datarecovery'])){ $datarecovery = $_REQUEST['datarecovery'] . "\n"; } else { $datarecovery = ""; } if (isset($_REQUEST['networkinstallation'])){ $networkinstallation = $_REQUEST['networkinstallation'] . "\n"; } else { $networkinstallation = ""; } if (isset($_REQUEST['mobilephoneissues'])){ $mobilephoneissues = $_REQUEST['mobilephoneissues'] . "\n"; } else { $mobilephoneissues = ""; } if (isset($_REQUEST['emailconfiguration'])){ $emailconfiguration = $_REQUEST['emailconfiguration'] . "\n"; } else { $emailconfiguration = ""; } if ( ereg( "[\r\n]", $name ) || ereg( "[\r\n]", $email ) ) { header( "Location: http://www.parkersmedia.com/byrne" ); } $mailcontent = "Name: ".$name; $mailcontent.= "\n\nEmail: ".$email; $mailcontent.= "\n\nInterested in: \n". $virusandmalwareremoval . $fullservice . $quickfix . $upgrades . $xbox360drivereplacement . $xbox360laserreplacement . $xbox360rrodrepair . $ps3drivereplacement . $ps3laserreplacement . $ps3ylodrepair . $databackup . $websites . $datarecovery . $networkinstallation . $mobilephoneissues . $emailconfiguration; $mailcontent.= "\n\nEnquiry: " . $enquiry; mail( "info@byrnecomputingservices.ie", "Enquiry from Byrne Computing Services", "$mailcontent", "From: $name <$email>" ); } header( "Location: http://www.parkersmedia.com/byrne/thankyou.shtml" ); ?> Any help on this would be great! Hi, Im making a form that contains 3 textboxes.. now i want my textboxes to contain only letters.. i used is_numeric for the validation but when i put' like.. "JUSHIRO1" my code will still accept it. can someone help me make a code that will validate my textbox to only accept letters. and one more.. when the user input in the textbox with a number a popup box will appear. Hi, I have a mistmatched tag <messagesss></message> BUT it still displays "Validated XML!" BUT then proceeds to the else that outputs each XML error! here is the XML: Code: [Select] <?xml version="1.0" encoding="utf-8"?> <email> <messagesss> <to> <toFirstName>Tove</toFirstName> <toLastName toType="common" style="swag">Smith</toLastName> </to> <from><fromdd/> <fromFirstName>Jani</fromFirstName> <fromLastName fromType="unique">Dravison</fromLastName> </from> </message> </email> Code: [Select] <?php $dom=new DOMDocument(); $dom->load("emailSimple.xml"); $isValidated=false; $dom->formatOutput = true; $dom->saveXML(); $errors=libxml_get_errors();//Returns array where each XML file line is an elem if(!file_exists("emailSimple.xml")) print "no such file!"; else if(strlen(file_get_contents("emailSimple.xml"))==0) print "File is empty!"; else if($dom) {//IF file exists and has content if(empty($errors)) print "Validated XML!";//isValidated=true so now shred! else { //CHECK if current XML file is Well-formed foreach($errors AS $error) {//FOR EACH ERROR OF CURRENT XML FILE TO CHECK echo "Error Code: ".$error->code."<br />"; echo "Error message: ".$error->message; //Column is the end of the line where error is echo "line".$error->line.", column".$error->column."<br />"; echo "----------------------------------------------<br /><br />"; } } libxml_clear_errors(); } ?> I need to validate first name, last name, street, suburb, postcode, email, status and date of birth. I tried to do this validation but gave me heaps of error and I messed up more. Spoiler if (empty($firstname)) {$errors[] =" First Name Can not be Empty <br> ";} if (empty($lastname)) {$errors[] =" Last Name Can not be Empty <br> ";} if (empty($street)) {$errors[] =" Street Can not be Empty <br> ";} if (empty($suburb)) {$errors[] =" Suburb Can not be Empty <br> ";} if (empty($postcode)) {$errors[] =" Postcode Can not be Empty <br> ";} // elseif (!is_numeric($postcode)) {$errors[] =" Postcode must be numeric ";} elseif(!preg_match("/\^\(\[0\-9\]\{5\}\(\[\-\\s\]\?\[0\-9\]\{4\}\)\?\)\$/", $postcode)) {$errors[] =" Please enter a valid post number <br> ";} if( !preg_match("/^[_a-z0-9-]+(.[_a-z0-9-]+)*@[a-z0-9-]+(.[a-z0-9-]+)*(.[a-z]{2,3})$/i", $myemail) ) {$errors[] =" You have entered and invalid email address <br> ";} if (empty($DOB)) {$errors[] =" Date only <br> ";} im looking to validate an email address before it gets sent to mysql database currently my code checks if an email address is present and if an email address already exists how do you check to see if an address contains a . and a @ symbol? Code: [Select] if($email == '') { $errmsg_arr[] = 'Email is missing'; $errflag = true; } if($email != '') { $qry = "SELECT * FROM users WHERE email='$email'"; $result = mysql_query($qry); if($result) { if(mysql_num_rows($result) > 0) { $errmsg_arr[] = 'Email address already in use'; $errflag = true; } @mysql_free_result($result); } else { die("Query failed"); } } Thanks in advance I am really new to using php validation, I think I may be on to what I am looking for but not very sure. I am trying to validate my form fields just incase someone forgets (name, subject, message, and email). Here is what I have so far. I was looking at an example on how to validate a phone number. Code: [Select] <!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>Contact</title> <link href="style.css" rel="stylesheet" type="text/css" /> </head> <body> <?php $first_name=$_POST['name']; $email_address=$_POST['email']; $subject=$_POST['subject']; $message=$_POST['text']; if(isset($_GET['submit'])) { if(preg_match("/^\(([ $_GET['email']) != ) { echo "The email field was invalid<BR>"; } else if(isset($_GET['submit'])) { if(preg_match("/^\(([ $_GET['name']) != "") { echo "The name field was invalid<BR>"; } else if(isset($_GET['submit'])) { if(preg_match("/^\(([ $_GET['subject']) != "") { echo "The subject field was invalid<BR>"; } else { mail("myemailaddress@gmail.com","Subject: $subject", $message, "From: $first_name <$email_address>"); echo "Thank you for using our mail form.<br/>"; echo "Your email has been sent."; } ?> </body> </html> I have a form validation script which is written in php.. I want to add a validation (in registration form) that if the desired username contains either admin or owner keyword user will have to change his user name.. I made the following code but it does not work.. if(strpos($user_name, "admin")>=0 || strpos($user_name, "moderator")>=0 || strpos($user_name, "owner")>=0) { $error=$error."You are not allowed to take such Username<br>"; $bool=false; } In this code i am not able to enter any username.. And if i change >= to > then "admin123" username is going to be valid... I am troubled .... help me out guyzzz -pranshu.a.11@gmail.com Hi, I have done email validation. At present it shows invalid email address if I kept blank but in the same time inserted the records in database. I want user to stay at the same page if anything is invalid. if(!empty($_POST['emailId'])){ if(preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/", $_POST['emailId'])){ $records['Email']=$_POST['emailId']; } else{ $emsg="Please enter valid Email address"; }} else{ $emsg="Please enter valid Email address"; } And I have used like <tr><td>Email id</td><td><input type="text" name="emailId"></td><td><?php echo ".$emsg." ;?></td></tr> Can anybody help me in this regard? First thing when i submit the form,values are not posted to the database table second thing its just displaying the error messages even if i submit the form.. third thing i dont know about the file upload i just got this code from google.. Hi, I am searching for a basic, easy to implement php form validation script that checks if the user has filled out a field, if they havent to tell them so. i have tried basic if statements but it refreshes the page and all the other fields that were filled in are clear. Anyone know of any tricks or scripts that are good? Thanks in advance. So, im trying to make my job a little easier. lol... I am constantly sending emails to the managers for escalations on calls... So I wrote this so far... (forgive my poor php skills, this is the first thing ive ever made. lol.) It does work so far, but, a friend wants to use it too, and Ive adapted it so he can enter his email address in, but, how can I make it so that it will validate only to send from @specificdomain.com ? Ive tried a few things, and just butchered it. lol.... Thanks for any help or tips. Code: [Select] <?php //$name = $_POST["email"]; $name = $_POST["name"]; $policynumber = $_POST["policynumber"]; $phonenumber = $_POST["phonenumber"]; $issue = $_POST["issue"]; $purchased = $_POST ["purchased"]; $infocheck = $_POST ["infocheck"]; $additionalinfo = stripslashes($_POST["additionalinfo"]); //checkbox value readout $mailcc = $_POST['sendmetoo']; $email_to = "SalesLevel2@specificurl.com"; // Who the email is to $email_from = $_POST['emailfrom']; // Who the email is from $email_subject = $policynumber.' - '.$issue; // The Subject of the email //here you can define whatever you want to... $headers = "MIME-Version: 1.0\r\n"; $headers .= "Content-type: text/plain; charset=UTF-8\r\n"; $headers .= "To: <".$email_to.">\r\n"; $headers .= "From: ".$email_from."\r\n"; //we control if sendmetoo is checked... if($mailcc == 'sendtome'){ $headers .= "Cc: ".$email_from."\r\n"; } //$headers .= "Bcc: noone@nowhere.com\r\n"; $email_message = "Sales Level 2,"; $email_message .= "\n\nPolicy Number: " .$policynumber; $email_message .= "\nClients Name: " .$name; $email_message .= "\nPhone Number: " .$phonenumber; $email_message .= "\nReason(s): " .$issue; $email_message .= "\nPurchased Already: " .$purchased; $email_message .= "\nAll info correct?: " .$infocheck; $email_message .= "\n\nAdditional Information: " .$additionalinfo; "\n\n\n\n". // Message that the email has in it //$headers = "From: ".$email_from; $ok = @mail($email_to, $email_subject, $email_message, $headers); if($ok) { echo "<font face=verdana size=2><center>Your message has been sent<br> to Sales Level 2<br> Click <a href=\"#\" onclick=\"history.back();\">here</a> to go back</center>"; } else { die("Sorry but the email could not be sent. Please go back and try again!"); } ?> Hello everyone. First of all let me introduce myself. I'm a Graduate web designer with emphasis on Design but I do like to dabble in code here and there. I love to design interfaces and mess around a little bit with Actionscript and i have a little experience with php. What I've got here is a php script (global license so I can use it) that I've attached to my web server. I've managed to tailor it so it validates all the fields I want, however the form still goes to my email whether or not there are validation errors. That is, even if the php picks up a validation error the data is still sent to the server. Can anyone please advise as to the script I need to solve this please? Obviously I don't want to burden someones email account with duff data when the site goes live :-) Thanks phprookie125 Code: [Select] <?php include "formvalidator.php"; $show_form=true; ?> <?php /***************************************/ //Start to build the email details $my_email = "myemailaddress@here.com"; $continue = "index.html"; /**/ $errors = array(); // Remove $_COOKIE elements from $_REQUEST. if(count($_COOKIE)){foreach(array_keys($_COOKIE) as $value){unset($_REQUEST[$value]);}} // Check all fields for an email header. function recursive_array_check_header($element_value) { global $set; if(!is_array($element_value)){if(preg_match("/(%0A|%0D|\n+|\r+)(content-type:|to:|cc:|bcc:)/i",$element_value)){$set = 1;}} else { foreach($element_value as $value){if($set){break;} recursive_array_check_header($value);} } } recursive_array_check_header($_REQUEST); if($set){$errors[] = "You cannot send an email header";} unset($set); // Validate email field. /**/if(isset($_REQUEST['email']) && !empty($_REQUEST['email'])) { if(preg_match("/(%0A|%0D|\n+|\r+|:)/i",$_REQUEST['email'])){$errors[] = "Email address may not contain a new line or a colon";} $_REQUEST['email'] = trim($_REQUEST['email']); if(substr_count($_REQUEST['email'],"@") != 1 || stristr($_REQUEST['email']," ")){$errors[] = "Email required.";}else{$exploded_email = explode("@",$_REQUEST['email']);if(empty($exploded_email[0]) || strlen($exploded_email[0]) > 64 || empty($exploded_email[1])){$errors[] = "You must include your email!";}else{if(substr_count($exploded_email[1],".") == 0){$errors[] = "Email address is invalid - editor note not validator.php";}else{$exploded_domain = explode(".",$exploded_email[1]);if(in_array("",$exploded_domain)){$errors[] = "Email address is invalid";}else{foreach($exploded_domain as $value){if(strlen($value) > 63 || !preg_match('/^[a-z0-9-]+$/i',$value)){$errors[] = "Email address is invalid"; break;}}}}}} } // Check referrer is from same site. if(!(isset($_SERVER['HTTP_REFERER']) && !empty($_SERVER['HTTP_REFERER']) && stristr($_SERVER['HTTP_REFERER'],$_SERVER['HTTP_HOST']))){$errors[] = "You must enable referrer logging to use the form";} // Check for a blank form. function recursive_array_check_blank($element_value) { global $set; if(!is_array($element_value)){if(!empty($element_value)){$set = 1;}} else { foreach($element_value as $value){if($set){break;} recursive_array_check_blank($value);} } } /**/ recursive_array_check_blank($_REQUEST); if(!$set){$errors[] = "You cannot send a blank form";} unset($set); // Display any errors and exit if errors exist. if(count($errors)){foreach($errors as $value){print "$value<br>";} exit;} if(!defined("PHP_EOL")){define("PHP_EOL", strtoupper(substr(PHP_OS,0,3) == "WIN") ? "\r\n" : "\n");} // Build message. function build_message($request_input){if(!isset($message_output)){$message_output ="";}if(!is_array($request_input)){$message_output = $request_input;}else{foreach($request_input as $key => $value){if(!empty($value)){if(!is_numeric($key)){$message_output .= str_replace("_"," ",ucfirst($key)).": ".build_message($value).PHP_EOL.PHP_EOL;}else{$message_output .= build_message($value).", ";}}}}return rtrim($message_output,", ");} if(true == $show_form) { $message = build_message($_REQUEST); $message = $message . PHP_EOL.PHP_EOL."-- ".PHP_EOL.""; $message = stripslashes($message); $subject = "Enquiry from Website"; $headers = "From: Website " . $_REQUEST['email']; mail($my_email,$subject,$message,$headers); ?> <!--html --> <!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>Auto Cleanse North East - Mobile Valeting and Detailing</title> <link rel = "stylesheet" type = "text/css" href = "../styles/mobile.css" /> <link rel = "stylesheet" type = "text/css" href = "../styles/formatting.css" /> <link rel = "stylesheet" type = "text/css" href = "../styles/style.css" /> <link rel = "stylesheet" type = "text/css" href = "../styles/nav.css" /> <link rel = "stylesheet" type = "text/css" href = "../styles/forms.css" /> </head> <body> <div id = "container"> <div id = "logoBanner"> <a href = "../autoCtmp.html"><img src="../images/top.png" alt="Auto Cleanse North East Logo - North East Best Mobile Valeting and Detailing" border="0" usemap="#Map" /></a> <map name="Map" id="Map"> <area shape="rect" coords="749,85,777,113" href="http://uk.linkedin.com/pub/sam-payne/20/a01/131" target="_new" alt="View Auto Cleanse LinkedIn Profile" /> <area shape="rect" coords="747,53,779,82" href="https://twitter.com/#!/AutoCleanseNE" target="_new" alt="Auto Cleanse North East is on Twitter!" /> <area shape="rect" coords="748,18,776,48" href="http://www.facebook.com/pages/Auto-Cleanse-North-East/232831036748006" target="_new" alt="View our Facebook Page!" /> </map> </div> <div id = "navigationBanner"> <img src="../images/navi.png" /> </div> <div id = "navText"><a class = "navLink" href = "autoCtmp.html">home</a></div> <!----> <div id = "navTextAbout"><a class = "navLinkAbout" href = "../about.html">ABOUT</a></div> <div id = "navTextPrices"><a class = "navLinkPrices" href = "../prices.html">PRICES & SERVICES</a></div> <div id = "navTextCarpets"><a class = "navLinkCarpets" href = "../carpets.html">CARPETS & UPHOLSTERY</a></div> <div id = "navTextGallery"><a class = "navLinkGallery" href = "../gallery.html">GALLERY</a></div> <div id = "navTextContact"><div id = "selected">CONTACT</div></div><!----> <div id = "topLinks"><a class ="topLinkStyle" href = "xxx.html">Mobile</a> | <a class = "topLinkStyle" href = "xxx.html">Low Graphics</a> </div> <div id = "mainBannerSub"> <div id = "textFormatSub"> <div id = "textFormatTitle">Contact Us!</div> <br /><?php if(isset($_POST['sendQuery'])) { $validator = new FormValidator(); $validator->addValidation("name","req","Please fill in Name"); $validator->addValidation("lastName", "req", "Please fill in lastName"); $validator->addValidation("contact_Email","email", "**Not a valid email please try again***"); $validator->addValidation("contact_Email","req","Please give an Email"); if($validator->ValidateForm()) { echo "<b>Thank you for contacting us! We have received your message and will contact you shortly<br /</b>"; $show_form=true; } else if (!isset($_POST['Submit'])) { echo "<B>Validation Errors:</B> - Please see below and correct"; $error_hash = $validator->GetErrors(); foreach($error_hash as $inpname => $inp_err) { echo "<p>$inpname : $inp_err</p>\n"; $show_form=false; } echo "<a class = 'emailLink' href = '../contact.html'>Click here to return to the contact page</a>"; } } ?> Hi, I am trying to set up a useername / password validation log in for a website - code below. I'm fairly new to php, so my understanding of what I have done is: config and env pick up some basic info including the servername, username, password and dbname for the connection, $_POST["username"] and $_POST["pwd"] are the values entered by the user on a previous log in page. Users is queried to bring back the data in $sql where the posted username ($userid) matches the UserName in the table. This is then checked to ensure there is one row returned - if not we go to test3.php If there is one row, the password entered on the log in ['pwd'] is compared to the password in the table. If they match we go to test1.php If they don't we go to test2.php test1.php test2.php and test3.php are holding pages which just display "Success", "incorrect password" or "No User" to check that this codeworks and will be replaced later.When I go through the login page and put an invalid user name, I get sent to test3.php - this is correct. However, if a put in a valid user name and a password, I get sent to test2.php (incorrect password) regardless of the password used being correct or not. Which makes me think the validation is not working.
This is the code from the input page for username & password:
<div style="display: table-row">
Thanks in advance for any assistance. <?php //get config and environment files - includes session script and database ID require_once("config.php"); require_once("env.php"); // Create connection $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $userid = $_POST["username"]; $sql = "SELECT UserID, UserName, Psswrd, FirstName, LastName, UserType FROM Users WHERE UserName = '$userid';"; $result = $conn->query($sql); $row = mysqli_fetch_assoc($result); if ($result->num_rows == 1) { $pwcheck = $row['Psswrd']; if(password_verify($_POST["pwd"],$pwcheck)) { header("Location: test1.php"); exit(); }else { header("Location: test2.php"); exit(); } }else { header("Location: test3.php"); exit(); } ?>Quote
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'm new to php, so please excuse my ignorance. Here's my issue: On my website, I want to ask the following question to validate the person filling in the form is a real person: Which is the hottest: FIRE or ICE ? Right now, my code is only set to accept all caps - which is confusing some of my customers. How to I update the following code, to allow caps and lowercase answers? if (empty( $_POST['validate'] ) || !ctype_upper( $_POST['validate'] ) || ($_POST['validate']!="ICE" and $_POST['validate']!="FIRE")){ $errors->add('empty_username', __('<strong>ERROR</strong>: Please check your validation answer.')); } |