I'm not sure why there is nothing being displayed after submitting my form. I think I understand PHP form validation for the most part, but I'm not sure where I'm going wrong. I do have JS validation as well, but this is for an assignment so I do have to do both.
My form looks like:
<?php include 'connect.php';?>
<form class="log-in-form" name="loginForm" action="sign-up-submit.php" method="post">
<p class="form-subtitle">Please create an account</p><br>
<input class="form-text" onfocus="this.placeholder = ''" type="text" placeholder="First Name" name="signupFirstName" id="signupFirstNameID"/><br>
<input class="form-text" onfocus="this.placeholder = ''" type="text" placeholder="Last Name" name="signupLastName" id="signupLastNameID"/><br>
<input class="form-text" onfocus="this.placeholder = ''" type="email" placeholder="Email Address" name="loginEmail" id="emailID" /><br>
<input class="form-text" onfocus="this.placeholder = ''" type="date" placeholder="Date of birthday" name="loginDate" id="dateID"/><br>
<input class="form-text" onfocus="this.placeholder = ''" type="password" placeholder="Password" name="loginPass" id="pwdID"/><br>
<input class="form-text" onfocus="this.placeholder = ''" type="password" placeholder="Verify Password" name="loginPassVerify" id="pwdVerifyID"/><br>
<input class="form-button" type="submit" value="Create Account" />
</form>
and my form validation looks like
<?php
$firstNameError = $lastNameError = $emailError = $dateError = $passwordError = $passVerifyError = "";
$firstName = $lastName = $email = $date = $password = $passVerify = "";
if (isset($_POST["signupFirstName"])) {
$firstNameError = "The first name is required";
} else {
$firstName = test_input($_POST["signupFirstName"]);
echo ($firstName);
}
if (isset($_POST["signupLastName"])) {
$lastNameError = "The last name is required";
} else {
$lastName = test_input($_POST["signupLastName"]);
echo ($lastName);
}
if (isset($_POST["loginEmail"])) {
$emailError = "An email address is required";
} else {
$email = test_input($_POST["loginEmail"]);
echo ($email);
}
if (isset($_POST["loginDate"])) {
$dateError = "You must enter a date of birth";
} else {
$date = test_input($_POST["loginDate"]);
echo ($date);
}
if (isset($_POST["loginPass"])) {
$passwordError = "Password is required";
} else {
$password = test_input($_POST["loginPass"]);
echo ($password);
}
if (isset($_POST["loginPassVerify"])) {
$passVerifyError = "You must verify your password";
} else {
$passVerify = test_input($_POST["loginPassVerify"]);
echo ($passVerify);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
It may help to simplify some of your script and form names. You have a lot of repetition that can be alleviated by a loop:
Simple Validation Example:
<?php
// Store your errors just in an array function because you could theoretically,
// in future, create a database-driven error system that would return
// an error code here based on a library of codes.
function error_code($key = false)
{
$error["fname"] = "The first name is required";
$error["lname"] = "The last name is required";
$error["email"] = "An email address is required";
$error["dob"] = "You must enter a date of birth";
$error["password"] = "Password is required";
$error["verify"] = "You must verify your password";
return (!empty($error[$key]))? $error[$key] : "Unknown Error.";
}
// I like to return false if empty, may or may not help you
function sanitize($data = false)
{
$data = trim($data);
$data = stripslashes($data);
// I personally like to turn quotes to special chars too
$data = htmlspecialchars($data,ENT_QUOTES);
return (!empty($data))? $data : false;
}
// Check that something has been submitted.
if(isset($_POST['fname'])) {
// Just loop through all your post values so you don't
// need so many if/else repetitions
foreach($_POST as $key => $value) {
// Will return some value or false
$value = sanitize($value);
// write to page if not false or else write an error code
echo ($value != false)? $value : error_code($key);
}
}
?>
Form:
<!-- I would suggest simplifying your id & name values, makes it a bit cleaner -->
<form class="log-in-form" name="loginForm" action="" method="post">
<p class="form-subtitle">Please create an account</p><br>
<input class="form-text" onfocus="this.placeholder = ''" type="text" placeholder="First Name" name="fname" id="fname" /><br>
<input class="form-text" onfocus="this.placeholder = ''" type="text" placeholder="Last Name" name="lname" id="lname"/><br>
<input class="form-text" onfocus="this.placeholder = ''" type="email" placeholder="Email Address" name="email" id="email" /><br>
<input class="form-text" onfocus="this.placeholder = ''" type="date" placeholder="Date of birthday" name="dob" id="dob"/><br>
<input class="form-text" onfocus="this.placeholder = ''" type="password" placeholder="Password" name="password" id="password"/><br>
<input class="form-text" onfocus="this.placeholder = ''" type="password" placeholder="Verify Password" name="verify" id="verify"/><br>
<input class="form-button" type="submit" value="Create Account" />
</form>
Related
I am making a simple Form the problem i am facing is when i submit the form values still remains in the field. and I want to clear it after SUCCESSFUL submission. Please help.
here is my code for the form..
<label class="w">Plan :</label>
<select autofocus="" name="plan" required="required">
<option value="">Select One</option>
<option value="FREE Account">FREE Account</option>
<option value="Premium Account Monthly">Premium Account Monthly</option>
<option value="Premium Account Yearly">Premium Account Yearly</option>
</select>
<br>
<label class="w">First Name :</label><input name="firstname" type="text" placeholder="First Name" required="required" value="<?php echo $_POST['firstname'];?>"><br>
<label class="w">Last Name :</label><input name="lastname" type="text" placeholder="Last Name" required="required" value="<?php echo $_POST['lastname'];?>"><br>
<label class="w">E-mail ID :</label><input name="email" type="email" placeholder="Enter Email" required="required" value="<?php echo $_POST['email'];?>"><br>
<label class="w">Password :</label><input name="password" type="password" placeholder="********" required="required" value="<?php echo $_POST['password'];?>"><br>
<label class="w">Re-Enter Password :</label><input name="confirmpassword" type="password" placeholder="********" required="required" value="<?php echo $_POST['confirmpassword'];?>"><br>
<label class="w">Street Address 1 :</label><input name="strtadd1" type="text" placeholder="street address first" required="required" value="<?php echo $_POST['strtadd1'];?>"><br>
<label class="w">Street Address 2 :</label><input name="strtadd2" type="text" placeholder="street address second" value="<?php echo $_POST['strtadd2'];?>"><br>
<label class="w">City :</label><input name="city" type="text" placeholder="City" required="required" value="<?php echo $_POST['firstname'];?>"><br>
<label class="w">Country :</label><select autofocus="" id="a1_txtBox1" name="country" required="required" placeholder="select one" value="<?php echo $_POST['country'];?>">
Any help would be appriciated
They remain in the fields because you are explicitly telling PHP to fill the form with the submitted data.
<input name="firstname" type="text" placeholder="First Name" required="required"
value="<?php echo $_POST['firstname'];?>">
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ HERE
Just remove this, or if you want a condition to not do so make a if statement to that echo or just cleanup the $_POST fields.
$_POST = array(); // lets pretend nothing was posted
Or, if successful, redirect the user to another page:
header("Location: success.html");
exit; // Location header is set, pointless to send HTML, stop the script
Which by the way is the prefered method. If you keep the user in a page that was reached through a POST method, if he refreshes the page the form will be submitted again.
You can use .reset() on your form.
$(".myform")[0].reset();
I was facing this similiar problem and did not want to use header() to redirect to another page.
Solution:
Use $_POST = array(); to reset the $_POST array at the top of the form, along with the code used to process the form.
The error or success messages can be conditionally added after the form.
Hope this helps :)
Here is the solution for when the for is submitted with the successful message all form fields to get cleared. for that set the values equals to false check the code below
<?php
$result_success = '';
$result_error = '';
$full_Name_error = $email_error = $msg_error = '';
$full_Name = $email = $msg = $phoneNumber = '';
$full_Name_test = $email_test = $msg_test = '';
//when the form is submitted POST Method and must be clicked on submit button
if ($_SERVER['REQUEST_METHOD'] == "POST" && isset($_POST['form-submit'])) {
$full_Name = $_POST['fullName'];
$email = $_POST['email'];
$phoneNumber = $_POST['phoneNumber'];
$msg = $_POST['message'];
// Form Validation for fullname
if (empty($full_Name)) {
$full_Name_error = "Name is required";
} else {
$full_Name_test = test_input($full_Name);
if (!preg_match("/^[a-z A-Z]*$/", $full_Name_test)) {
$full_Name_error = "Only letters and white spaces are allowed";
}
}
//Form Validation for email
if (empty($email)) {
$email_error = "Email is required";
} else {
$email_test = test_input($email);
if (!filter_var($email_test, FILTER_VALIDATE_EMAIL)) {
$email_error = "Invalid Email format";
}
}
//Form Validation for message
if (empty($msg)) {
$msg_error = "Say atleast Hello!";
} else {
$msg_test = test_input($msg);
}
if ($full_Name_error == '' and $email_error == '' and $msg_error == '') {
// Here starts PHP Mailer
date_default_timezone_set('Etc/UTC');
// Edit this path if PHPMailer is in a different location.
require './PHPMailer/PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->isSMTP();
/*Server Configuration*/
$mail->Host = 'smtp.gmail.com'; // Which SMTP server to use.
$mail->Port = 587; // Which port to use, 587 is the default port for TLS security.
$mail->SMTPSecure = 'tls'; // Which security method to use. TLS is most secure.
$mail->SMTPAuth = true; // Whether you need to login. This is almost always required.
$mail->Username = ""; // Your Gmail address.
$mail->Password = ""; // Your Gmail login password or App Specific Password.
/*Message Configuration*/
$mail->setFrom($email, $full_Name); // Set the sender of the message.
$mail->addAddress(''); // Set the recipient of the message.
$mail->Subject = 'Contact form submission from your Website'; // The subject of the message
/*Message Content - Choose simple text or HTML email*/
$mail->isHTML(true);
// Choose to send either a simple text email...
$mail->Body = 'Name: ' . $full_Name . '<br>' . 'PhoneNumber: ' . $phoneNumber . '<br>' . 'Email: ' . $email . '<br><br>' . 'Message: ' . '<h4>' . $msg . '</h4>'; // Set a plain text body.
// ... or send an email with HTML.
//$mail->msgHTML(file_get_contents('contents.html'));
// Optional when using HTML: Set an alternative plain text message for email clients who prefer that.
//$mail->AltBody = 'This is a plain-text message body';
// Optional: attach a file
//$mail->addAttachment('images/phpmailer_mini.png');
if ($mail->send()) {
$result_success = "Your message was sent successfully! " .
//Here is the solution for when the for is submitted with the successful message all form fields to get cleared.
$full_Name;
$full_Name = false;
$email = false;
$phoneNumber = false;
$msg = false;
} else {
$result_error = "Something went wrong. Check your Network connection and Please try again.";
}
}
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
The POST data which holds the submitted form data is being echoed in the form, eg:
<input name="firstname" type="text" placeholder="First Name" required="required"
value="<?php echo $_POST['firstname'];?>"
Either clear the POST data once you have done with the form - ie all inputs were ok and you have actioned whatever your result from a form is.
Or, once you have determined the form is ok and have actioned whatever you action from the form, redirect the user to a new page to say "all done, thanks" etc.
header('Location: thanks.php');
exit();
This stops the POST data being present, it's know as "Post/Redirect/Get":
http://en.wikipedia.org/wiki/Post/Redirect/Get
The Post/Redirect/Get (PRG) method and using another page also ensures that if users click browser refresh, or back button having navigated somewhere else, your form is not submitted again.
This means if your form inserts into a database, or emails someone (etc), without the PRG method the values will (likely) be inserted/emailed every time they click refresh or revisit the page using their history/back button.
Put the onClick function in the button submit:
<input type="text" id="firstname">
<input type="text" id="lastname">
<input type="submit" value="Submit" onClick="clearform();" />
In the <head>, define the function clearform(), and set the textbox value to "":
function clearform()
{
document.getElementById("firstname").value=""; //don't forget to set the textbox id
document.getElementById("lastname").value="";
}
This way the textbox will be cleared when you click the submit button.
I was just trying to fix same error, I finally fixed it, so I will copy to you part of the code, maybe it helps you.
<input type="text" name="usu" id="usu" value="<?php echo $usu;?>" ></input>
<input type="text" name="pass" id="pass" value="<?php echo $varpass;?>"></input>
those are the inputs I wanted to clean after pressing my button.
And here php code:
$query= "INSERT INTO usuarios (tipo, usuario, password) VALUES ('".$vartipo."', '".$usu."', '".$varpass."')";
if (!mysqli_query($conexion,$query)){
die('Error: ' . mysqli_error($conexion));
}
else{
$usu = '';
$varpass= '';
$result = '<div class="result_ok">El usuario se ha registrado con éxito! <div>';
}
$usu = '';
$varpass= '';
those are the lines that cleans the inputs :D
this code will help you
if($insert){$_POST['name']="";$_POST['content']=""}
If you want your form's field clear, you must only add a delay in the onClick event like:
<input name="submit" id="MyButton" type="submit" class="btn-lg" value="ClickMe" onClick="setTimeout('clearform()', 2000 );"
onClick="setTimeout('clearform()', 1500 );" . in 1,5 seconds its clear
document.getElementById("name").value = ""; <<<<<<just correct this
document.getElementById("telephone").value = ""; <<<<<correct this
By clearform(), I mean your clearing-fields function.
// This file is PHP.
<html>
<?php
if ($_POST['submit']) {
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$password = $_POST['password'];
$confirmpassword = $_POST['confirmpassword'];
$strtadd1 = $_POST['strtadd1'];
$strtadd2 = $_POST['strtadd2'];
$city = $_POST['city'];
$country = $_POST['country'];
$success = '';
// Upon Success.
if ($firstname != '' && $lastname != '' && $email != '' && $password != '' && $confirmpassword != '' && $strtadd1 != '' && $strtadd2 != '' && $city != '' && $country != '') {
// Change $success variable from an empty string.
$success = 'success';
// Insert whatever you want to do upon success.
} else {
// Upon Failure.
echo '<p class="error">Fill in all fields.</p>';
// Set $success variable to an empty string.
$success = '';
}
}
?>
<form method="POST" action="#">
<label class="w">Plan :</label>
<select autofocus="" name="plan" required="required">
<option value="">Select One</option>
<option value="FREE Account">FREE Account</option>
<option value="Premium Account Monthly">Premium Account Monthly</option>
<option value="Premium Account Yearly">Premium Account Yearly</option>
</select>
<br>
<label class="w">First Name :</label><input name="firstname" type="text" placeholder="First Name" required="required" value="<?php if (isset($firstname) && $success == '') {echo $firstname;} ?>"><br>
<label class="w">Last Name :</label><input name="lastname" type="text" placeholder="Last Name" required="required" value="<?php if (isset($lastname) && $success == '') {echo $lastname;} ?>"><br>
<label class="w">E-mail ID :</label><input name="email" type="email" placeholder="Enter Email" required="required" value="<?php if (isset($email) && $success == '') {echo $email;} ?>"><br>
<label class="w">Password :</label><input name="password" type="password" placeholder="********" required="required" value="<?php if (isset($password) && $success == '') {echo $password;} ?>"><br>
<label class="w">Re-Enter Password :</label><input name="confirmpassword" type="password" placeholder="********" required="required" value="<?php if (isset($confirmpassword) && $success == '') {echo $confirmpassword;} ?>"><br>
<label class="w">Street Address 1 :</label><input name="strtadd1" type="text" placeholder="street address first" required="required" value="<?php if (isset($strtadd1) && $success == '') {echo $strtadd1;} ?>"><br>
<label class="w">Street Address 2 :</label><input name="strtadd2" type="text" placeholder="street address second" value="<?php if (isset($strtadd2) && $success == '') {echo $strtadd2;} ?>"><br>
<label class="w">City :</label><input name="city" type="text" placeholder="City" required="required" value="<?php if (isset($city) && $success == '') {echo $city;} ?>"><br>
<label class="w">Country :</label><select autofocus="" id="a1_txtBox1" name="country" required="required" placeholder="select one" value="<?php if (isset($country) && $success == '') {echo $country;} ?>">
<input type="submit" name="submit">
</form>
</html>
Use value="<?php if (isset($firstname) && $success == '') {echo $firstname;} ?>"
You'll then have to create the $success variable--as I did in my example.
You can check this also
<form id="form1" method="post">
<label class="w">Plan :</label>
<select autofocus="" name="plan" required="required">
<option value="">Select One</option>
<option value="FREE Account">FREE Account</option>
<option value="Premium Account Monthly">Premium Account Monthly</option>
<option value="Premium Account Yearly">Premium Account Yearly</option>
</select>
<br>
<label class="w">First Name :</label><input name="firstname" type="text" placeholder="First Name" required="required" ><br>
<label class="w">Last Name :</label><input name="lastname" type="text" placeholder="Last Name" required="required" ><br>
<label class="w">E-mail ID :</label><input name="email" type="email" placeholder="Enter Email" required="required" ><br>
<label class="w">Password :</label><input name="password" type="password" placeholder="********" required="required"><br>
<label class="w">Re-Enter Password :</label><input name="confirmpassword" type="password" placeholder="********" required="required"><br>
<label class="w">Street Address 1 :</label><input name="strtadd1" type="text" placeholder="street address first" required="required"><br>
<label class="w">Street Address 2 :</label><input name="strtadd2" type="text" placeholder="street address second" ><br>
<label class="w">City :</label>
<input name="city" type="text" placeholder="City" required="required"><br>
<label class="w">Country :</label>
<select autofocus id="a1_txtBox1" name="country" required="required" placeholder="select one">
<option>Select One</option>
<option>UK</option>
<option>US</option>
</select>
<br>
<br>
<input type="reset" value="Submit" />
</form>
After submitting the post you can redirect using inline javascript like below:
echo '<script language="javascript">window.location.href=""</script>';
I use this code all the time to clear form data and reload the current form. The empty href reloads the current page in a reset mode.
You can also use unset function to do this e.g. below is my code where I verify an email existence.
if($mail->check($email)){
$status = 'succ';
$statusMsg = 'Given email <'.$email.'> exists!';
unset($_REQUEST["name"]);
unset($_REQUEST["email"]);
unset($_REQUEST["comment"]);
}elseif(verifyEmail::validate($email)){
$status = 'err';
$statusMsg = 'Given email <'.$email.'> is valid, but does not exist!';
}else{
$status = 'err';
$statusMsg = 'Given email <'.$email.'> is not valid, not exist!';
}
}else{
$status = 'err';
$statusMsg = 'Enter the email address that is to be verified';
}
This can be used after the mysql command of Insert a record in the table and that does it. It resets the values entered there in the fields.
It is possible to ask a browser not to follow the redirect headers, in this case a user can still refresh the page.
I think the best solution is to destroy all the data sent by the form, then attempt to redirect the user to another page.
<?php
// Destroys data _POST
foreach ($_POST as $key => $value) {
unset($_POST[$key]);
}
// redirect user
header("Location: other_page.html");
// terminate the current script
exit();
I have a simple form to submit testimonials, I also was having trouble clearing the form, what I did was after the query is submitted successfully I and before redirecting to another page I cleared the imputs $name =''; ect. The page submitted and redirected with no errors.
This my first time using PHP validation and my validations are working perfectly.
How do i style the validation, do i select the echo function or do i have to change my validation code to be able to style it. I have tried using a span and echoing out a error function and changing the echo's to the error function e.g $emailErr but not luck, the validations does not work. any suggestions?
HTML
<!-- <div id="first">-->
<input type="email" id="email" name="email" placeholder="Email Address" value='' required><!--<span class="error"><!--<?php //echo $c_emailErr; ?></span>-->
<br>
<figure>
<input class ="login-field" type="password" id="pass1" name="pass1" value="" placeholder="Password" maxlength="30" required><!--<span class="error"><1--<?php //echo $c_pass1Err; ?></span>-->
<input class ="login-field" type="password" id="pass2" name="pass2" value="" placeholder=" Confirm password" maxlength="30" required><!--<span class="error"><!--<?php //echo $c_pass2Err; ?></span>-->
<div id="messages"></div>
</figure>
<p class="remember_me">
</p>
<input type="submit" name="submit" value="Register" id="submit_button" class="btn btn-default">
<br>
</form>
PHP
<?php
if (isset($_POST['submit'])) {
$reg_errors = array();
$c_email = $_POST['email'];
$c_pass1 = $_POST['pass1'];
$c_pass2 = $_POST['pass2'];
$emailErr = $pass1Err = $pass2Err = "";
// $c_email = $c_pass1 = $c_pass2 = "";
// Remove all illegal characters from email
// $c_email = filter_var($c_email, FILTER_SANITIZE_EMAIL);
//Checking the email address
if (!filter_var($c_email, FILTER_VALIDATE_EMAIL) === false) {
echo("<b> This is a valid email address </b>");
} else {
echo("<b> Email is not a valid email address</b>");
}
if (strlen($c_pass1) <= '8') {
echo "<b>Your Password Must Contain At Least 8 Characters!</br>";
//check passwords
}elseif ($c_pass1 == $c_pass2) {
$q = "INSERT INTO Cus_Register(Cus_Email,Cus_Password,Cus_confirm_password) VALUES (?,?,?)";
$stmt = mysqli_prepare($dbc, $q);
//new
// $stmt = mysqli_prepare($dbc, $insert_c);
//debugging
//$stmt = mysqli_prepare($dbc, $insert_c) or die(mysqli_error($dbc));
mysqli_stmt_bind_param($stmt, 'sss', $c_email, $c_pass1, $c_pass2);
if ($q) {
echo "<script> alert('registration sucessful')</script>";
}
} else {
echo "<b>Oops! Your passwords do not </b>";
}
}
?>
say you had tag for text and you have the code
<?
echo '<t>this is some text';
?>
to add styles all you simply have to do is style the "t" tag like so in css
t{
font-size:3px;
background-color:red;
// other styles
}
This is my first time validating a form.
I have got stuck on validating the email in theory it seems like it should work but it doesn't.
The following code only works when i remove the email validation:
if ($c_pass1 == $c_pass2) {
} else {
echo "Oops! Your passwords do not match ";
not to sure where i have gone wrong. The validation literally does nothing. is there a better way to validate an email address?
HTML
<!-- <div id="first">-->
<input type="email" id="email" name="email" placeholder="Email Address" value='' required><!--<span class="error"><?php //echo $c_emailErr; ?></span>-->
<br>
<figure>
<input class ="login-field" type="password" id="pass1" name="pass1" value="" placeholder="Password" maxlength="30" required><!--<span class="error"><?php //echo $c_pass1Err; ?></span>-->
<input class ="login-field" type="password" id="pass2" name="pass2" value="" placeholder=" Confirm password" maxlength="30" required><!--<span class="error"><?php //echo $c_pass2Err; ?></span>-->
<div id="messages"></div>
</figure>
<p class="remember_me">
</p>
<input type="submit" name="submit" value="Register" id="submit_button" class="btn btn-default">
<br>
</form>
PHP
$c_email = $_POST['email'];
$c_pass1 = $_POST['pass1'];
$c_pass2 = $_POST['pass2'];
$c_emailErr = $c_pass1Err = $c_pass2Err = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
//Validates email
if (empty($_POST["email"])) {
$c_emailErr = "You Forgot to Enter Your Email!";
} else {
$c_email = test_input($_POST["email"]);
// check if e-mail address syntax is valid
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$c_emailErr )) {
$c_emailErr = "You Entered An Invalid Email Format";
}
}
if ($c_pass1 == $c_pass2) {
$q = "INSERT INTO Cus_Register(Cus_Email,Cus_Password,Cus_confirm_password) VALUES (?,?,?)";
$stmt = mysqli_prepare($dbc, $q);
//new
// $stmt = mysqli_prepare($dbc, $insert_c);
//debugging
//$stmt = mysqli_prepare($dbc, $insert_c) or die(mysqli_error($dbc));
mysqli_stmt_bind_param($stmt, 'sss', $c_email, $c_pass1, $c_pass2);
if ($q) {
echo "<script> alert('registration sucessful')</script>";
}
} else {
echo "<b>Oops! Your passwords do not </b>";
}
}
}
?>
To validate Email Instead Of doing this: if (empty($_POST["email"])) { Try doing this if(!filter_var($_POST["email"], FILTER_VALIDATE_EMAIL) === false
That should take care of the email part
Now for the password part try this:
if ($_POST[$c_pass1 != $c_pass2]) {echo'wrong password';}else{echo 'good password';}
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input onclick="this.value=''" type="text" name="first_name" value="First Name">
<input onclick="this.value=''" type="text" name="last_name" value="Last Name">
<input onclick="this.value=''" type="text" name="pwd" value="The Passcode">
<input name="submit" type="submit" value="Submit" class="submit_">
<textarea name="comments" id="comments" rows="4" cols="50"></textarea>
</form>
PHP :
if(isset($_POST['submit']))
{
$name = mysql_real_escape_string($_POST['first_name']);
$pwd = mysql_real_escape_string($_POST['pwd']);
$text = mysql_real_escape_string($_POST['comments']);
// print_r($_POST);
if(is_null($text)) {
debug_to_console('some fields empty');
echo "<p class=\"warning\">* Your Message Did Not Contain Any Characters.</p>";
}
else if($name === 'First Name'){
debug_to_console('name isnt set');
echo "<p class=\"warning\">* You Have Not Entered Your First Name Correctly.</p>";
}
else if($pwd !== 'XyZ'){
debug_to_console('password not set');
echo "<p class=\"warning\">* Passcodes Do Not Match.</p>";
} else {
Keeps returning 'password not set' even though the form input matches the variable. Used print_r and $pwd states XyZ.
tried removing onClick from the form input. I'm assuming this is a caps thing?
Please help, thank you.
Check $pwd with
var_dump($pwd);
I do believe $pwd is a string (because you use !== instead of !=) AND doesn't contain: XyZ
(if you didn't change the value in input field pwd, its value is still: The Passcode)
I have a form that populates a database, and I'm having trouble with the error handling. I want the errors to show in a small pop up window on the same pg.
<form id="form1" name="form1" method="post" action="mailform.php" onsubmit="MM_validateForm('Name','','R','Business Name','','R','Email Address','','R','How selling product','','R','Where did you hear about us','','R');return document.MM_returnValue">
<div style="color:#FF0000; text-align:center;"><?php if(!empty($_GET['err_msg'])){echo $_GET['err_msg'];} ?></div>
<fieldset>
<legend>Contact form</legend>
<p class="first">
<label for="name">First Name</label>
<input type="text" name="First Name" id="first_name" size="30" value="<?=htmlentities($profiledata['First_Name'])?>" />
</p>
<p class="first">
<label for="name">Last Name</label>
<input type="text" name="Last Name" id="last_name" size="30" value="<?=htmlentities($profiledata['Last_Name'])?>" />
</p>
<p>
<label for="name">Phone Number</label>
<input type="text" name="Phone Number" id="phone number" size="30" value="<?=$profiledata['Phone_Number']?>" />
</p>
<p>
<label for="email">Business Name</label>
<input type="text" name="Business Name" id="business name" size="30" value="<?=htmlentities($profiledata['Business_Name'])?>" />
</p>
<p>
<label for="email">Web Address</label>
<input type="text" name="Web Address" id="web address" size="30" value="<?=$profiledata['Web_Address']?>" />
</p>
<p>
<label for="email">Email</label>
<input type="text" name="Email Address" id="email address" size="30" value="<?=$profiledata['Email_Address']?>" />
</p>
<p>
<img src="CaptchaSecurityImages.php?width=100&height=40&characters=5" /><br />
<label for="security_code">Security Code: </label><input id="security_code" name="security_code" type="text" />
</p>
</fieldset>
<fieldset>
<p>
<label for="message">Describe how you plan on selling this product</label>
<textarea name="How selling product" id="How selling product" cols="30" rows="4"><?=htmlentities($profiledata['How_selling_product'])?></textarea>
</p>
<p>
<label for="message">Where did you hear about us?</label>
<textarea name="Where did you hear about us" id="Where did you hear about us" cols="30" rows="4"><?=htmlentities($profiledata['Where_did_you_hear_about_us'])?></textarea>
</p>
</fieldset>
<p class="submit"><button type="submit">Send</button></p>
<input name="mailform_address" type="hidden" value="email#address.com" />
</form>
Error handling:
function valid_email($str)
{
return ( ! preg_match("/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*#([a-z0-9\-]+\.)+[a-z]{2,6}$/ix", $str)) ? FALSE : TRUE;
}
function is_url($str)
{
return ( ! preg_match("/^((www)\.)?((\w+|[\d]?+)+(\.|\-)(\w+[\d]?+))+(\w)$/", $str)) ? FALSE : TRUE;
}
function valid_phone($str)
{
$Num = $str;
$Num = ereg_replace("([ ]+)","",$Num);;
$Num = eregi_replace("(\(|\)|\-|\+)","",$Num);
if(!is_numeric($Num))
{
return FALSE;
}
else
return TRUE;
}
$form_field = array(
'First_Name' => '',
'Last_Name' => '',
'Business_Name' => '',
'Phone_Number' => '',
'Web_Address' => '',
'Email_Address' => '',
'How_selling_product' => '',
'Where_did_you_hear_about_us' => '',
);
foreach($form_field as $key => $value){$profiledata[$key]=trim($_POST[$key]);}
$_SESSION['profiledata'] = $profiledata;
$emailto = NULL;
$emailmessage = "Dealer Contact Form\n";
$emailsubject = "Dealer Contact Form";
if(!empty($_POST)){
//echo "<pre>";print_r($_POST);die;
if( $_SESSION['security_code'] != $_POST['security_code'] || empty($_SESSION['security_code'] ) ) {
// Insert your code for showing an error message here
$err_msg = 'Sorry, you have provided an invalid security code';
header("Location: reseller.php?err_msg=".urlencode($err_msg));
return;
} else {
unset($_SESSION['security_code']);
}
$fname = html_entity_decode(trim($_POST['First_Name']));
$lname = html_entity_decode(trim($_POST['Last_Name']));
$company = html_entity_decode(trim($_POST['Business_Name']));
$phone = html_entity_decode(trim($_POST['Phone_Number']));
$website = html_entity_decode(trim($_POST['Web_Address']));
$email = html_entity_decode(trim($_POST['Email_Address']));
$notes = "Lead Source: ".html_entity_decode(trim($_POST['Where_did_you_hear_about_us']))."\n";
$notes .= "Selling Method: ".html_entity_decode(trim($_POST['How_selling_product']));
if(!valid_phone($phone)){
$err_msg = 'Please enter valid Phone Number.';
header("Location: reseller.php?err_msg=".urlencode($err_msg));
return;
}
if(!is_url($website)){
$err_msg = 'Please enter valid Web Address.';
header("Location: reseller.php?err_msg=".urlencode($err_msg));
return;
}
if(!valid_email($email)){
$err_msg = 'Please enter valid Email.';
header("Location: reseller.php?err_msg=".urlencode($err_msg));
return;
}
if(!stristr($website,"http://") && !stristr($website,"https://") && $website){
$website = "http://".$website;
}
$res = mysql_query("SELECT in_customer_id FROM tbl_customer WHERE st_company_name = '".addslashes($company)."'");
if(mysql_num_rows($res)){
$err_msg = 'Business Name already exists';
header("Location: reseller.php?err_msg=".urlencode($err_msg));
return;
}
$res = mysql_query("SELECT st_user_name,st_user_email_id FROM tbl_admin_user WHERE st_user_email_id='".addslashes($email)."' AND flg_is_delete=0");
if(mysql_num_rows($res)){
$err_msg = 'Email already exists';
header("Location: reseller.php?err_msg=".urlencode($err_msg));
return;
}
I'd appreciate some help or at least a nudge in the right direction. Thanks!
Depending on what kind of 'popup' you want, you will probably want to implement some client side javascript that displays a nicely formatted message that makes use of the message that you send back from the server.
I'd look at using JQuery if it was me.
Is this okay?
<html>
<head>
<script>
function Start(page) {
OpenWin = this.open(page, "CtrlWindow", "toolbar=no,menubar=no,location=no,scrollbars=yes,resizable=yes,width=600,height=200,left="
+((window.screen.width-600)/2)+",top="+((window.screen.height-200)/3)+"" );
}
</script>
</head>
<body onload="Start('child.htm')">
This is parent.
</body>
</html>