This is the code i have used for online Registration
Validation is not working when i submit it another page,form is submitting to another page without any validation.i just need too know how to submit it with validation, can some one help out
<?php
// define variables and set to empty values
$nameErr = $cnameErr = $mobilenoErr = $emailErr = $cityErr= $postalcodeErr = $addressErr = "";
$name = $cname = $mobileno = $email = $city= $postalcode = $address = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["cname"])) {
$cnameErr = "Company Name is required";
} else {
$cname = test_input($_POST["cname"]);
}
if (empty($_POST["mobileno"])) {
$mobilenoErr = "Mobile Number is required";
}else {
$mobileno = test_input($_POST["mobileno"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[789][0-9]{9}$/",$mobileno)) {
$mobilenoErr = "Not A Valid Number";
}
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["city"])) {
$cityErr = "City is required";
} else {
$city = test_input($_POST["city"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$city)) {
$cityErr = "Only letters and white space allowed";
}
}
if (empty($_POST["postalcode"])) {
$postalcodeErr = "Postal Code is required";
} else {
$postalcode = test_input($_POST["city"]);
}
if (empty($_POST["address"])) {
$addressErr = "Address is required";
} else {
$address = test_input($_POST["address"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<div class="gridContainer clearfix">
<div id="div1" class="fluid"><!-- header ends here-->
<div id="header" class="fluid">
<div class="fluid logo_container zeroMargin_tablet">
<div class="fluid logo_mvc"></div>
<!-- logo_mvc ends here-->
<div class="fluid logo_gsm"></div>
<!-- logo_gsm ends here-->
</div>
<!-- logo_container ends here-->
</div>
<div class="fluid imageslide zeroMargin_desktop">
<div class="fluid imageslide_gs zeroMargin_desktop"></div>
<!-- imageslide_gs ends here-->
<div class="fluid imageslide_content">
<h1>IP Product Introduction and VoIP PBX
Appliance Training Day # Toronto</h1>
</div><!-- imageslide_content ends here-->
<div class="fluid imageslide_product"></div>
<!-- imageslide_product ends here-->
</div><!-- imageslide ends here-->
<div class="fluid content">
<div class="fluid content_det">
<h3>Event information</h3>
<p>Please join us at the Fairfield Inn & Suites Toronto Airport where Grandstream will offer four different sessions during the day. </p>
<h3>Introduction to Grandstream IP products</h3>
<p><b>8:45am - 10:15am</b><br/>
Introduction to Grandstream, and basic information on Grandstream products including ATAs, gateways, routers and telephones. </p>
<h3>Introduction to IP cameras IP and Surveillance products</h3>
<p><b>12:45pm - 2:15pm</b><br/>
Basic information on IP cameras and surveillance products, and the introduction of the brand new GVR3550 Network Video Recorder. </p>
<h3>Advanced Technical Training for UCM VoIP PBX's</h3>
<p><b>2:30pm - 4:30pm</b><br/>
This session will focus on the advanced features of the UCM series, including the new features of the upcoming software and the brand new UCM6510 VoIP PBX for T1 networks. </p>
</div><!-- content_det ends here--><div class="fluid contet_form">
<h2>Register Now</h2>
<form method="post" action="Submission.php">
<div class="fluid div_form"><label><b>First name *:</b></label>
<input type="text" size="20px" name="name" placeholder="Enter Your Name Here" value="<?php echo $name; ?>"/><span class="error"><?php echo $nameErr;?></span>
</div>
<div class="fluid div_form"><label><b>Company Name *:</b></label>
<input type="text" size="20px" name="cname" placeholder="Enter Your Company Name Here" value="<?php echo $cname; ?>"/><span class="error"><?php echo $cnameErr;?></span></div>
<div class="fluid div_form"><label><b>Mobile Number *:</b></label>
<input type="text" size="20px" name="mobileno" placeholder="Enter Your Mobile Number Here" value="<?php echo $mobileno; ?>"/><span class="error"><?php echo $mobilenoErr?></span>
</div>
<div class="fluid div_form"><label><b>Email Id *:</b></label>
<input type="email" size="20px" name="email" placeholder="Enter Your Email Id Here" value="<?php echo $email; ?>"/><span class="error"><?php echo $emailErr?></span></div>
<div class="fluid div_form"><label><b>City *:</b></label>
<input type="text" size="20px" name="city" placeholder="Enter Your City Name Here" value="<?php echo $city;?>"/><span class="error"><?php echo $cityErr?></span></div>
<div class="fluid div_form"><label><b>Postal Code *:</b></label>
<input type="text" size="20px" name="postalcode" placeholder="Enter Postal Code Here" value="<?php echo $postalcode; ?>"/><span class="error"><?php echo $postalcodeErr?></span>
</div>
<div class="fluid div_form"><label><b>Address *:</b></label>
<input type="text" size="20px" name="address" placeholder="Enter Address Here" value="<?php echo $address; ?>"/><span class="error"><?php echo $addressErr?></span></div>
<button name="submit">Submit</button>
</form>
</div><!-- contet_form ends here-->
</div><!-- content ends here-->
</div><!-- div1 ends here-->
</div>
</body>
The validation has to happens when the request reaches the server. Your flow is like:
form displayed in browser -> user clicks submit -> data submitted to Submission.php -> validation should happen here.
Put your validation code in Submission.php.
To me it seems you are new to PHP form handling. For beginners reinventing the wheel and is dangerous as it's so easy to open up security flaws in your script. Use a framework or CMS that can handle forms for you (e.g., WordPress and Contact Form 7 or just use something easy as Zebra Form or something complete like CakePHP, Laravel or Symfony.
Just don't do everything yourself unless you really know what you are doing. It might take some time to get started, but it will definitely pay off in the long run.
Carefully check your action in form attribute. If you mention page name in form attribute then it will submit another page without validation. If you want validation in same page then remove page name from your action in form attribute. Other wise put validation checking in another page, which is mention in your action in form attribute.
Related
I would like to validate a form on the server before submitting it to a database, i managed to write a php code that shows error messages for invalid inputs once the user clicks submit in the form, which is step one, however, step two is to prevent the form from submitting which is what i would like to know how , because despite error messages showing that input was invalid, the input goes to the data base. i tried to define a "$valid = true" variable , and then return it as false after each error message, but it didnt help ..
<?php
// define variables and set to empty values
$staffErr = $emailErr = $subjectErr = $problemErr = $descriptionErr= "";
$staffname = $email = $subject = $problem_type = $description = "";
$valid = true;
// staff name validation:
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["staffname"])) {
$staffErr = "Staff Name is required";
$valid = false;
} else {
$staff_name = test_input($_POST["staffname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z-' ]*$/",$staffname)) {
$staffErr = "Only letters and white space allowed";
$valid = false;
}
}
// email validation:
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Please enter a valid email.";
}
}
// subject validation:
if (empty($_POST["subject"])) {
$subjectErr = "Subject is required";
} else {
$subject = test_input($_POST["subject"]);
// check if subject only contains letters and whitespace
if (!preg_match("/^[a-zA-Z-' ]*$/",$subject)) {
$nameErr = "Only letters and white space allowed";
}
}
// problem type validation:
if (empty($_POST["problem_type"])) {
$problemErr = "Problem type is required";
} else {
$problem_type = test_input($_POST["problem_type"]);
}
// description validation:
if (empty($_POST["description"])) {
$descriptionErr = "A Description is required";
} else {
$description = test_input($_POST["description"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<form method="post" onsubmit=" return formSubmit()" action="#">
<div class="error1" id= "errorMsg">* Required Fields</div>
<div class="error" id= "errorMsg1">*<?php echo $staffErr; ?></div>
<div>
<label for="staff_name"><b>Staff Name:</b></label>
<input class="field" id="staff_name" name="staffname" onclick=" return staffValidation()" onchange=" return staffValidation()" id="subject" type="text" placeholder="Staff Name" >
</div><br>
<div class="error" id= "errorMsg2">*<?php echo $emailErr; ?></div>
<div>
<label for="email"><b>Email:</b></label>
<input class="field" id="email1" name="email" onclick=" return emailValidation()" onchange=" return emailValidation()" type="email" placeholder="staff#wearview.com" >
</div><br>
<div class="error" id= "errorMsg3">*<?php echo $subjectErr; ?></div>
<div>
<label for="subject"><b>Subject:</b></label>
<input class="field" name="subject" id="subject1" onclick=" return subjectValidation()" onchange=" return subjectValidation()" type="text" placeholder="Subject Title" >
</div><br>
<div class="error" id= "errorMsg4">*<?php echo $problemErr; ?></div>
<div>
<select onclick=" return problemValidation()" onchange=" return problemValidation()" class="field4" name="problem_type" id="problemtypes">
<option value="">Problem Type</option>
<option value="Hardware">Hardware</option>
<option value="Software">Software</option>
<option value="Software&Hardware">Software & Hardware</option>
<option value="Other">Other</option>
</select>
</div><br>
<div class="error" id= "errorMsg5">*<?php echo $descriptionErr; ?></div>
<div>
<textarea class="field2" id="description1" name="description" onclick=" return descriptionValidation()" onchange=" return descriptionValidation()" placeholder="Description goes here" rows="15" cols="90"></textarea>
</div>
<div>
<button class="field3" type="submit" class="btn">Submit</button>
<input type="checkbox" id="notify" name="notify" value="">
<label for="notify">Inform me by email when issue is resolved.</label>
</div>
</form>
Here's an example (all PHP) without Javascript but with better security & email check. Tested on a working server. If you want an example with a properly protected insert statement, let me know and I'll add to this answer.
<?php
$name = $response_name = $email = $response_email = ""; // Clear variables
// Name (trims white space and doesn't accept names under 2 characters or over 20 characters)
if (isset($_POST['myform'])) {
$name = mysqli_real_escape_string($con, $_POST['name']);
if (empty($name) || strlen(trim($name)) < 2 || strlen(trim($name)) > 20) {
$response_name = "bad name";
}
// Email (checks for correct email format and tests a response from the email domain server example: gmail.com)
$email = mysqli_real_escape_string($con, $_POST['email']);
$email_host = strtolower(substr(strrchr($email, "#"), 1));
$email_host = idn_to_ascii($email_host.'.');
if (filter_var($email, FILTER_VALIDATE_EMAIL) === false || !checkdnsrr($email_host, "MX")) {
$response_email = "bad email";
}
if ($response_name=="" && $response_email=="") {
echo "data ok, proceed";
// Now send to MySQL table...
}
}
echo "
<form method='post'>
<label for='name'><b>Name:</b> $response_name</label>
<input name='name' type='text' value='$name' placeholder='Enter your name'>
<label for='email'><b>Email:</b> $response_email</label>
<input name='email' type='email' value='$email' placeholder='Enter your email' >
<button type='submit' name='myform'>SUBMIT</button>
</form>
";
?>
Note: For forms, Javascript is good for initial data error detection but to be really secure you would want to check with PHP and so if you're already using Javascript for forms you should be using AJAX as it's much more user friendly (no page reloading required) and you'll be able to reference an external PHP file which keeps code neater and tidier, at least IMO!
I know this question has been asked many times before over the years. However, I am facing the wall after attempting to correctly implement all the potential solutions that others have listed in this post: "https://stackoverflow.com/questions/17242346/php-session-lost-after-redirect".
I know my session variables exist before using "header("location: nextPage.php");" to redirect. As soon as I put the line in the code, the session variables disappear. I am posting all my code because I did tried all the solutions I have seen. So maybe, the problem is my code and someone can find what I am doing wrong.
Thank you in advance.
<?php
session_save_path('/home/myHome/cgi-bin/tmp');
session_start();
$fnameErr = $lnameErr = $ssnErr = $dofbErr = $occpErr = $filstatErr = "";
$fname = $mname = $lname = $ssn = $dofb = $occp = $filstat = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
global $fnameErr, $lnameErr;
if (empty($_POST["fname"])) {
$fnameErr = "Your first name is required";
} else {
$fname = test_input($_POST["fname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z-' ]*$/",$fname)) {
$fnameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["lname"])) {
$lnameErr = "Your last name is required";
} else {
$lname = test_input($_POST["lname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z-' ]*$/",$lname)) {
$lnameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["ssn"])) {
$ssnErr = "Your social security number is required";
} else {
$ssn = test_input($_POST["ssn"]);
// check if name only contains letters and whitespace
if (!preg_match("/[0-9]{3}-[0-9]{2}-[0-9]{4}/",$ssn)) {
$ssnErr = "There is an error in your social security number";
}
}
if (empty($_POST["dofb"])) {
$dofbErr = "Your date of birth is required";
} else {
$dofb = $_POST["dofb"];
}
if (empty($_POST["occp"])) {
$occpErr = "Your occupation is required";
} else {
$occp = test_input($_POST["occp"]);
}
if (isset($_REQUEST["filstat"]) && $_REQUEST["filstat"] == "disabled selected hidden") {
$filstatErr = "Your filing status is required";
} else {
$filstat = test_input($_POST["filstat"]);
}
if(isset($_POST['next'])){
if ($fnameErr == "" && $lnameErr == "" && $ssnErr == "" && $dofbErr == "" && $occpErr == "" && $filstatErr == "") {
session_write_close();
header("location: nextPage.php");
exit();
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<script src="https://kit.fontawesome.com/1bd5f284bd.js" crossorigin="anonymous"></script>
<title>Welcome</title>
</head>
<body>
<div class="grid-container">
<div class="header">
<h1>someTitle</h1> <h5>subTitle</h5>
</div>
<div class="menu">
<ul>
<li><a class="active" href="index.php"><i class='fas fa-user-alt'></i>Personal Info</a></li>
<li><i class='fas fa-city'></i>W-2 Employer info</li>
<li><i class='fas fa-dollar-sign'></i>W-2 Earned Income</li>
<li><i class='fas fa-hand-holding-usd'></i>Cash Income</li>
<li><i class='fas fa-book-reader'></i>Review</li>
<li><i class='fas fa-upload'></i>Submit</li>
</ul>
</div>
<div class="main">
<h2>Please complete your personal information below</h2>
<p class="error">* required field</p>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
<label for="fname">First Name:<span class="error"> * <?php echo $fnameErr;?></span></label>
<input type="text" id="fname" name="fname" maxlength="40" placeholder="Your name.." value="<?php echo $fname; ?>">
<label for="mname">Middle Initial:</label>
<input type="text" id="mname" name="mname" maxlength="1" value="<?php echo $mname; ?>">
<label for="lname">Last Name:<span class="error"> * <?php echo $lnameErr;?></span></label>
<input type="text" id="lname" name="lname" maxlength="50" placeholder="Your last name.." value="<?php echo $lname; ?>">
<label for="ssn">Social Security Number:<span class="error"> * <?php echo $ssnErr;?></span></label>
<input type="text" id="ssn" name="ssn" minlength="9" maxlength="11" placeholder="000-00-0000" value="<?php echo $ssn; ?>" onBlur = "myFunc()">
<label for="dofb">Date of Birth:<span class="error"> * <?php echo $dofbErr;?></span></label>
<input type="date" id="dofb" name="dofb" maxlength="10" min="1930-01-01" max="2000-12-31" value="<?php echo $dofb; ?>">
<label for="occp">Occupation<span class="error"> * <?php echo $occpErr;?></span></label>
<input type="text" id="occp" name="occp" maxlength="40" placeholder="Your principal work" value="<?php echo $occp; ?>">
<label for="filstat">Filing Status:<span class="error"> * <?php echo $filstatErr;?></span></label>
<select id="filstat" name= "filstat" required>
<option value="disabled selected hidden">Choose Filing Status</option>
<option value="Single">Single</option>
<option value="Married filing jointly">Married filing jointly</option>
<option value="Head of Household">Head of Household</option>
</select>
<input type="reset" value="Reset">
<input type="submit" name="next" value="Next">
</form>
</div>
<div class="instructions">
<h2>Help Center</h2>
<p>Instructions to what needs to be done go here.</p>
</div>
<div class="footer">
<p>© Copyright 2020–2021 websiteName ® All rights reserved</p>
</div>
</div>
<script type="text/javascript">
function myFunc() {
var patt = new RegExp("\d{3}[\-]\d{2}[\-]\d{4}");
var x = document.getElementById("ssn");
var res = patt.test(x.value);
if(!res){
x.value = x.value
.match(/\d*/g).join('')
.match(/(\d{0,3})(\d{0,2})(\d{0,4})/).slice(1).join('-')
.replace(/-*$/g, '');
}
}
</script>
</body>
</html>
I'm learning coding and created a simple form where error messages are
displayed just below each input field. However, when I check the form
the success message appears at the same time as error messages instead
of displaying when all the fields are correctly entered and form
validated. Can you please help. Thank yo in advance. Here is my
code.
</php>
$errorMessage = "";
$successMessage = "";
$emailError = "";
$emailconfirmError = "";
$nameError = "";
$messageError = "";
$servicesError = "";
$name = $email = $emailConfirm = $services = $message = "";
$email = isset($_POST['email']) ? $_POST['email'] : '';
$emailConfirm = isset($_POST['emailConfirm']) ? $_POST['emailConfirm'] : '';
if ($_POST) {
if (!$_POST['email']) {
$emailError .="The email is required";
}
if (!$_POST['emailConfirm']) {
$emailconfirmError .="Please confirm your email <br>";
}
if ($_POST['emailConfirm'] && $email != $emailConfirm) {
$emailconfirmError .="The email addresses do not match <br>";
}
if (!$_POST['name']) {
$nameError .="The name field is required <br>";
}
if (!$_POST['services']) {
$servicesError .="Please select a service required <br>";
}
if (!$_POST['message']) {
$messageError .="The message field is required <br>";
}
if ($_POST['email'] && filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) === false) {
$emailError .= "The email address is invalid.<br>";
}
if ($name = $email = $emailConfirm = $services = $message != "") {
echo $emailError;
echo $emailconfirmError;
echo $name;
echo $services;
echo $message;
}else {
$emailTo = "kamala_guliyeva#hotmail.com";
$services = $_POST['services'];
$message = $_POST['message'];
$headers = "From: ".$_POST['email'];
if (mail($emailTo, $services, $message, $headers)) {
$successMessage = '<div class="alert alert-success" role="alert">Thank you for your message. We\'ll get back to you ASAP!</div>';
} else {
$errorMessage = '<div class="alert alert-danger" role="alert"><p>Your message couldn\'t be sent - please try again</div>';
}
}
}
and HTML
<div id="quote">
<div class="container">
<h2 class="section-title">Request a Quote</h2>
<hr align="left" width="8%" class="style-one">
<br>
<div><? echo $errorMessage.$successMessage; ?></div>
<form id="quoteForm" method="post">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<input type="email" class="form-control" style="height:60px" id="email" name="email" placeholder="Your email">
<label class="error" id="emailError"><?php echo $emailError; ?></label>
</div>
<div class="form-group">
<input type="email" class="form-control" style="height:60px" id="emailConfirm" name="emailConfirm" placeholder="Re-type your email">
<label class="error" for="e-mailConfirm" id="emailconfirmError"><?php echo $emailconfirmError; ?></label>
</div>
<div class="form-group">
<input type="name" class="form-control" id="name" style="height:60px" name="name" placeholder="Your Name">
<label class="error" for="name" id="nameError"><?php echo $nameError; ?></label>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<select class="form-control" id="services" name="services" style="height:60px">
<option value="">Select Services</option>
<option value="Installation">Installation</option>
<option value="Repair">Repair</option>
<option value="Service and Maintenance">Service and Maintenance</option>
</select>
<label class="error" for="services" id="servicesError"><?php echo $servicesError; ?></label>
</div>
<div class="form-group">
<textarea class="form-control" id="message" name="message" placeholder="Message" style="height: 163px;" cols="35"></textarea>
<label class="error" for="message" id="messageError"><?php echo $messageError; ?></label>
</div>
</div>
</div>
<div class="form-row text-center">
<div class="col-12">
<button type="submit" style="width:10rem" class="btn quoteButton pt-3 pb-3 text-align-center">Get a Quote</button>
</div>
</div>
</form>
</div>
</div>
You've a few problems there...
So first thing is how you are doing your checks.
if(!$_POST) {
is not a valid way of checking that a post has occurred you need to do something like
if(isset($_POST) && !empty($_POST)) {
would be more appropriate as you are checking if the POST array is actually set and then that it is not empty the && operator is a short circuit operator so if either condition isn't met then the check will fail.
Similarly on your comparisons saying if(!$_POST['email']) { isn't valid because you're effectively asking "if the email part of the post array is not true" where as you need to be asking "if it's not blank and is a valid email address"
You need to be aware of the difference between = == and === operators. You can find some more information here: The 3 different equals
And also the filter_var function here: http://php.net/manual/en/function.filter-var.php
if($_POST['email']!=="" && filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
//all good
} else {
//set your error message
}
you can use regular expressions to validate 'name' see preg_match in the manual http://php.net/manual/en/function.preg-match.php
Aside from all of this if you want to have real time monitoring of the fields and the error messages etc you're going to have to look at incorporating Javascript and using AJAX to communicate with your script and then parse the response back into the appropriate div.
Have a look at Rasmus 30 second AJAX tutorial will give you a starting point for this http://rajshekhar.net/blog/archives/85-Rasmus-30-second-AJAX-Tutorial.html
However it is better practice to do both client and server side validation hope this helps even if it is not a complete answer per sé.
This code works fine in seperated file named form.php, but when i paste it to
wordpress theme page it does not even validate form and not even send mail of course. Why is there no any action after i clikced submit button in wordpress theme?
Anyone can help me to solve problem?
get_header();
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$nameError = $mailError = $messageError = '';
function validate($data){
if(empty($data)){
return false;
}else{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
}
//Validate name input
if(!validate($_POST['name'])){
$nameError = 'Polje ime je obavezno.';
}else{
if (!preg_match("/^[a-zA-Z ]*$/",$_POST['name'])) {
$nameError = "Polje moze sadrzavati samo slova i razmak";
}
}
//Validate email input
if(!validate($_POST['email'])){
$mailError = 'Polje email je obavezno';
}else{
if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$mailError = "Nevazeća email adresa";
}
}
//Validate message textarea
if(!validate($_POST['message'])){
$messageError = 'Molimo unesite poruku';
}
if(empty($nameError) && empty($mailError) && empty($messageError)){
//Create the body
$body = "Ime: {$_POST['name']}\n\nPoruka: {$_POST['message']}";
//Make it no longer than 70 characters long
$body = wordwrap($body, 70);
//Send the mail
mail('example#example.com', 'Contact Form Submission',
$body,
"From: {$_POST['email']}");
//Print a message
echo '<p><em>Thank you for contacting me. I will reply some day.
</em></p>';
}else{
echo '<p style="font-weight: bold; color: #C00">Please fill out
the
form completley.</p>';
}
}
HTML Code that is placed in same file as php validation
<section class="contact-img">
<div class="container-fluid">
<div class="row">
<?php the_post_thumbnail(); ?>
</div>
</div>
</section>
<section class="contact">
<div class="container">
<div class="row">
<?php dynamic_sidebar('contact-page'); ?>
<div class="col-md-12">
<h4 class="col-xs-12 text-center"><strong>Ostavite
poruku</strong></h4>
</div>
</div>
</div>
<div class="container">
<div class="row">
<div class="col-xs-10 col-xs-offset-1 col-sm-6 col-sm-offset-3">
<form method="POST" action="<?php echo
htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div class="form-group">
<input type="text" class="form-control" name="name"
value="" placeholder="Ime">
<div><?php if(isset($nameError)) echo $nameError; ?>
</div>
</div>
<div class="form-group">
<input type="text" class="form-control" name="email"
value="" placeholder="E-mail">
<div><span class="error"><?php if(isset($mailError))
echo $mailError; ?></span></div>
</div>
<div class="form-group">
<textarea class="form-control" name="message" rows="3"
placeholder="Poruka"></textarea>
<div><span class="error"><?php
if(isset($messageError)) echo $messageError; ?></span></div>
</div>
<input class="btn btn-default" type="button" name="button"
value="Pošalji">
</form>
</div>
</div>
</div>
</section>
You have a syntax error (white page of death, if error reporting is off)
$nameError = 'Polje moze sadrzavati samo slova i razmak;
Should be:
$nameError = 'Polje moze sadrzavati samo slova i razmak';
Another thing that might get you is your name validation Regex is to simple, it doesn't account for things like Jane Doe-Smith, or J o h n S m i t h or j or even '', an empty string.
I would use something like this:
if(!preg_match("/^([a-z]+)\s+(?:([a-z]+)\s+)?([-a-z]+)$/i" , $_POST['name'])){
$nameError = 'Polje moze sadrzavati samo slova i razmak;
}
Regex:
([a-z]+) matches a though z (first 2 capture groups)
\s+ matches one or more space
(?...) non-capture group ? optionally, middle name
([-a-z]+) matches - and a though z (for hyphenated last names)
\i case insensitive flag.
Regex Test
Test cases:
John Smith {match}
John E Smith {match}
Jane J Doe-Smith {match}
John {no match}
Which is still a small sample size, but should cover most English names ( not sure what language this is Polje moze).
I once dated a girl many many years ago with a hyphenated last name ... lol.
The last thing is to turn on display errors and set error reporting to a value like E_ALL (for development). I'd say use ini_set('display_errors', '1') and error_reporting() but they won't catch syntax errors in the same file (generally).
I'm trying to get a form pre-filled using a query string and let the user make any necessary changes then press submit and have the form process and send an email to an administrator for doing whatever it is they need to do with the information.
I'm using PHP to populate the form and I started with a tutorial from NetTuts for the email form processing because it did validation inline. Hopefully validation isn't necessary because all the fields are pre-filled but I wanted to have the form check just to make sure the user doesn't clear a field before submitting the form. I'm at a loss as to why the form won't process correctly.
The only changes between my form and the tutorial are in variable names, the inclusion and some $_GET superglobals to grab the form data from the query string, and the use of echo to fill out the form from the $_GET superglobals instead of the session data should the user submit the form without filling everything out. Everything else has been copied verbatim from the tutorial.
Any help solving this problem, even if it's rethinking how I might go about doing this, would be much appreciated.
Below is the code for the form page and the processing page.
Form Page:
<?php
session_start();
// site root folder
$root_folder = "/meetingplannersignup";
//get values of displayed form fields from URL
$FirstName= $_GET['FirstName'];
$LastName = $_GET['LastName'];
$Organization = $_GET['Organization'];
$EmailAddress = $_GET['EmailAddress'];
$Phone = $_GET['Phone'];
$EventType = $_GET['EventType'];
$EventName = $_GET['EventName'];
$EventLocation = $_GET['EventLocation'];
$HotelName = $_GET['HotelName'];
$EventStart = $_GET['EventStart'];
$EventEnd = $_GET['EventEnd'];
// get values of hidden form fields from URL
$ExtReferenceID = $_GET['ExtReferenceID'];
$City = $_GET['City'];
$State = $_GET['State'];
$ZipCode = $_GET['ZipCode'];
$CountryCode = $_GET['CountryCode'];
?>
<!DOCTYPE html>
<!--[if IE 8]><html class="no-js lt-ie9" lang="en" > <![endif]-->
<!--[if gt IE 8]><!--><html class="no-js" lang="en" > <!--<![endif]-->
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Simplify Event Management with GroupMAX</title>
<link rel="stylesheet" href="<?php echo $root_url ?>/assets/css/bootstrap.css">
</head>
<body>
<div class="container">
<!-- begin main nav -->
<nav class="navbar navbar-static-top navbar-inverse" role="navigation">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-main-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse navbar-main-collapse">
<ul class="nav navbar-nav">
<li class="active">home</li>
<li>fill out form</li>
</ul>
</div><!-- /.navbar-collapse -->
</nav>
<!-- end main nav -->
<div class="row">
<div class="col-lg-12">
<h1>Simplify Event Management with GroupMAX</h1>
<h3>Impress Your Attendees. Optimize Your Event.</h3>
<hr />
</div>
</div>
<div class="row">
<div class="col-lg-6">
<h4>Included Features are:</h4>
<ul>
<li><strong>Event Booking Websites – </strong>Passkey’s award winning booking website allows for personalized hotel reservation website where attendees can make, modify or cancel their hotel bookings directly into that group's contracted block.</li>
<li><strong>Integrated with Event Registration - </strong>RegLink™ is an integration technology that can link any online planner registration solution to Passkey's best-in-class hotel reservation system, allowing meeting planners to integrate hotel reservations directly into their event registration process.</li>
<li><strong>Event Dashboard – </strong>With Event Dashboard Planners can track their events, manage their lists and monitor reservations anytime online. With Passkey’s LiveView Dashboards, meeting planners can get an instant snapshot of their event in a fun, interactive environment. </li>
<li><strong>SmartAlerts™ - </strong>Automatic e-mails containing vital event information that are automatically sent out to a list of recipients at specific intervals or critical event milestones.</li>
</ul>
</div>
<div class="col-lg-6">
<div class="row">
<div class="col-lg-12">
<!-- begin error processing -->
<div class="well">
<?php
//init variables
$cf = array();
$sr = false;
if(isset($_SESSION['cf_returndata'])){
$cf = $_SESSION['cf_returndata'];
$sr = true;
}
?>
<div id="errors" class="alert alert-danger<?php echo ($sr && !$cf['form_ok']) ? ' show_alert' : ''; ?>">
<p>There were some problems with your form submission:</p>
<ul>
<?php
if(isset($cf['errors']) && count($cf['errors']) > 0) :
foreach($cf['errors'] as $error) :
?>
<li><?php echo $error ?></li>
<?php
endforeach;
endif;
?>
<?php
//init variables
$cf = array();
$sr = false;
if(isset($_SESSION['cf_returndata'])){
$cf = $_SESSION['cf_returndata'];
$sr = true;
}
?>
</ul>
</div>
<p id="success" class="alert alert-success<?php echo ($sr && $cf['form_ok']) ? ' show_alert' : ''; ?>">Thanks for your message! We will get back to you ASAP!</p>
<!-- end error processing -->
<!-- begin form -->
<fieldset>
<legend>Your Information</legend>
<p>Please review the pre-filled information and correct any inaccurate information prior to submitting the form.</p>
<form method="post" action="process.php">
<div class="form-group">
<label>First Name</label>
<input type="text" class="form-control" id="FirstName" value="<?php echo ($sr && !$cf['form_ok']) ? $cf['posted_form_data']['FirstName'] : '' ?><?php echo $FirstName; ?>">
</div>
<div class="form-group">
<label>Last Name</label>
<input type="text" class="form-control" id="LastName" value="<?php echo $LastName; ?>">
</div>
<div class="form-group">
<label>Company/Organization</label>
<input type="text" class="form-control" id="Organization" value="<?php echo $Organization; ?>">
</div>
<div class="form-group">
<label>Email Address</label>
<input type="text" class="form-control" id="EmailAddress" value="<?php echo $EmailAddress; ?>">
</div>
<div class="form-group">
<label>Phone Number</label>
<input type="text" class="form-control" id="Phone" value="<?php echo $Phone; ?>">
</div>
<div class="form-group">
<label>Event Type</label>
<input type="text" class="form-control" id="EventType" value="<?php echo $EventType; ?>">
</div>
<div class="form-group">
<label>Event Name</label>
<input type="text" class="form-control" id="EventName" value="<?php echo $EventName; ?>">
</div>
<div class="form-group">
<label>Event Location</label>
<input type="text" class="form-control" id="EventLocation" value="<?php echo $EventLocation; ?>">
</div>
<div class="form-group">
<label>Hotel Name</label>
<input type="text" class="form-control" id="HotelName" value="<?php echo $HotelName; ?>">
</div>
<div class="form-group">
<label>Start/Arrival Date</label>
<input type="text" class="form-control" id="EventStart" value="<?php echo $EventStart; ?>">
</div>
<div class="form-group">
<label>End Date</label>
<input type="text" class="form-control" id="EventEnd" value="<?php echo $EventEnd; ?>">
</div>
<hr />
<input type="submit" value="Submit" class="btn btn-primary" />
<!--hidden fields-->
<input type="hidden" id="ExtReferenceID" value="<?php echo $ExtReferenceID; ?>">
<input type="hidden" id="City" value="<?php echo $City; ?>">
<input type="hidden" id="State" value="<?php echo $State; ?>">
<input type="hidden" id="ZipCode" value="<?php echo $ZipCode; ?>">
<input type="hidden" id="CountryCode" value="<?php echo $CountryCode; ?>">
</form>
<?php unset($_SESSION['cf_returndata']); ?>
</fieldset>
</div>
<!-- end form -->
</div>
</div>
</div>
</div>
</div>
</body>
</html>
Processing Page:
<?php
if( isset($_POST) ){
//form validation vars
$formok = true;
$errors = array();
//submission data
$ipaddress = $_SERVER['REMOTE_ADDR'];
$date = date('d/m/Y');
$time = date('H:i:s');
//form data
$FirstName = $_POST['FirstName'];
$LastName = $_POST['LastName'];
$Organization = $_POST['Organization'];
$EmailAddress = $_POST['EmailAddress'];
$Phone = $_POST['Phone'];
$EventType = $_POST['EventType'];
$EventName = $_POST['EventName'];
$EventLocation = $_POST['EventLocation'];
$HotelName = $_POST['HotelName'];
$EventStart = $_POST['EventStart'];
$EventEnd = $_POST['EventEnd'];
// hidden form fields
$ExtReferenceID = $_POST['ExtReferenceID'];
$City = $_POST['City'];
$State = $_POST['State'];
$ZipCode = $_POST['ZipCode'];
$CountryCode = $_POST['CountryCode'];
//validate form data
//validate First Name is not empty
if(empty($FirstName)){
$formok = false;
$errors[] = "You have not entered a First Name";
//validate Last Name is not empty
} elseif (empty($LastName)){
$formok = false;
$errors[] = "You have not entered a Last Name";
//validate Company/Organization is not empty
} elseif (empty($Organization)){
$formok = false;
$errors[] = "You have not entered a Company or organization";
//validate email address is not empty
} elseif (empty($EmailAddress)){
$formok = false;
$errors[] = "You have not entered an email address";
//validate email address is valid
} elseif (!filter_var($EmailAddress, FILTER_VALIDATE_EMAIL)){
$formok = false;
$errors[] = "You have not entered a valid Email Address";
//validate Last Name is not empty
} elseif (empty($Phone)){
$formok = false;
$errors[] = "You have not entered a Phone Number";
//validate Last Name is not empty
} elseif (empty($EventType)){
$formok = false;
$errors[] = "You have not entered an Event Type";
//validate Last Name is not empty
} elseif (empty($EventName)){
$formok = false;
$errors[] = "You have not entered an Event Name";
//validate Last Name is not empty
} elseif (empty($EventLocation)){
$formok = false;
$errors[] = "You have not entered an Event Location";
//validate Last Name is not empty
} elseif (empty($HotelName)){
$formok = false;
$errors[] = "You have not entered a Hotel Name";
//validate Last Name is not empty
} elseif (empty($EventStart)){
$formok = false;
$errors[] = "You have not entered an Event Start Date";
//validate Last Name is not empty
} elseif (empty($EventEnd)){
$formok = false;
$errors[] = "You have not entered an Event End Date";
}
//send email if all is ok
if($formok){
$headers = "From: meetingplannersignup#passkey.com" . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$emailbody = "<p>You have recieved a new meeting planner signup registration:</p>
<p><strong>First Name: </strong> {$FirstName}</p>
<p><strong>Last Name: </strong> {$LastName}</p>
<p><strong>Company/Organization: </strong> {$Organization}</p>
<p><strong>Email Address: </strong> {$EmailAddress}</p>
<p><strong>Phone: </strong> {$Phone}</p>
<hr />
<p><strong>Event Type: </strong> {$EventType}</p>
<p><strong>Event Name: </strong> {$EventName}</p>
<p><strong>Event Location: </strong> {$EventLocation}</p>
<p><strong>Hotel Name: </strong> {$HotelName}</p>
<p><strong>Event Start Date: </strong> {$EventStart}</p>
<p><strong>Event End Date: </strong> {$EventEnd}</p>
<hr />
<p><strong>Reference ID: </strong> {$ExtReferenceID}</p>
<p><strong>City: </strong> {$City}</p>
<p><strong>State: </strong> {$State}</p>
<p><strong>Zip Code: </strong> {$ZipCode}</p>
<p><strong>Country Code: </strong> {$CountryCode}</p>
<hr />
<p>This message was sent from the IP Address: {$ipaddress} on {$date} at {$time}</p> ";
mail("stuart#monderer.com","Meeting Planner Signup",$emailbody,$headers);
}
//what we need to return back to our form
$returndata = array(
'posted_form_data' => array(
'FirstName' => $FirstName,
'LastName' => $LastName,
'EmailAddress' => $EmailAddress,
'Organization' => $Organization,
'Phone' => $Phone,
'EventType' => $EventType,
'EventName' => $EventName,
'EventLocation' => $EventLocation,
'HotelName' => $HotelName,
'EventStart' => $EventStart,
'EventEnd' => $EventEnd,
'ExtReferenceID' => $ExtReferenceID,
'City' => $City,
'State' => $State,
'ZipCode' => $ZipCode,
'CountryCode' => $CountryCode
),
'form_ok' => $formok,
'errors' => $errors
);
//if this is not an ajax request
if(empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) !== 'xmlhttprequest'){
//set session variables
session_start();
$_SESSION['cf_returndata'] = $returndata;
//redirect back to form
header('location: ' . $_SERVER['HTTP_REFERER']);
}
}
Several problems:
1. isset($_POST) will always be true
In your processing page you check for:
if( isset($_POST) )
This will always evaluate to true even if $_POST is empty. You should check for a specific field to try and guess is the form was submitted
2. You use id instead of name
The form values that are sent via POST are identified via their name, not via their id. In the HTML you can keep the id attribute but for each field that is to be POSTed you must add a name attribute:
<input type="text" class="form-control" name="LastName" id="LastName" value="<?php echo $LastName; ?>">
$_POST['LastName'] is empty if you only identify your form control with an id.
I haven't checked the rest but you should try to fix those points first.