Send mail with PHP by validating google reCAPTCHA - php

I want to send a mail with PHP with validation by google reCAPTCHA. I write the following code. It seems everything is ok. but it is showing a error every time Something is wrong. Please check the error bellow. please help me someone.
<?php
if (isset($_POST['submit'])) {
$name = trim($_POST['name']);
$email = $_POST['email'];
$subject = trim($_POST['subject']);
$message = $_POST['message'];
// Google reCAPTCHA
require_once('recaptchalib.php');
$privatekey = "6Lcnk_USAAAAAHhVB97WBfaXq4-XN1DkCHjLO3j-";
$resp = recaptcha_check_answer ($privatekey, $_SERVER["REMOTE_ADDR"], $_POST["recaptcha_challenge_field"], $_POST["recaptcha_response_field"]);
if (!$resp->is_valid) {
// What happens when the CAPTCHA was entered incorrectly
$captchaErr = "The reCAPTCHA wasn't entered correctly. Please try it again.";
} else {
// Your code here to handle a successful verification
$validCaptcha = ture;
}
// Validate email address with PHP
if (empty($email)) {
$emailErr = "Email is required";
}else if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
$emailErr = "Invalid email format";
}else{
$validEmail = true;
}
// Validate name with PHP
if (!empty($name)) {
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space are allowed.";
}
} else {
$validName = true;
}
// Validate message with PHP
if ( strlen($message) < 15 ) {
$messageErr = "At least 15 letters required.";
} else {
$validMessage = true;
}
// If all validation are true than send mail
$to = 'example#yahoo.com';
$headers = 'From: $name <$email>'."\r\n";
if ( $validCaptcha && $validEmail && $validName && $validMessage ) {
$sendMail = mail( $to, $subject, $message, $headers );
}
// Show message to user
if ( $sendMail ) {
$sendMailSucc = '<div class="">Email has been sent successful.</div>';
} else {
$sendMailErr = '<div class="error">Something is wrong. Please check the error bellow.</div>';
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>reCAPTCHA</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container">
<script type="text/javascript">
var RecaptchaOptions = {
// red, white, blackglass, clean
theme : 'clean'
};
</script>
<form action="" class="contact_form" method="POST">
<div class="confirmation">
<?php echo $sendMailSucc; ?><?php echo $sendMailErr; ?>
</div>
<div>
<label for="">Full Name:</label>
<input type="text" name="name" value="<?php echo $name; ?>">
<span class="error"><?php echo $nameErr; ?></span>
</div>
<div>
<label for="">Email:</label>
<input type="text" name="email" value="<?php echo $email; ?>">
<span class="error"><?php echo $emailErr; ?></span>
</div>
<div>
<label for="">Subject:</label>
<input type="text" name="subject" value="<?php echo $subject; ?>">
</div>
<div>
<label for="message">Message:</label>
<textarea name="message" id="" cols="30" rows="10"><?php echo $message; ?></textarea>
<span class="error"><?php echo $messageErr; ?></span>
</div>
<div>
<?php
require_once('recaptchalib.php');
$publickey = "6Lcnk_USAAAAADYvvrn9_CE1-HvAjke4GlcQolYE"; // you got this from the signup page
echo recaptcha_get_html($publickey);
?>
<span class="error"><?php echo $captchaErr; ?></span>
</div>
<div>
<input type="submit" name="submit" value="Send">
</div>
</form>
</div>

Related

Contact Form for my website not working in php [duplicate]

This question already has answers here:
PHP mail function doesn't complete sending of e-mail
(31 answers)
Closed 3 years ago.
I am trying to make a contact form for my website in php, but it seems something wrong somewhere, which i am unable to locate. Can you please help me to locate the error in the following code will be of great help and suggest further improvement on this.
Will of great help.
Thanks in advance.
<?php
// Message Vars
$msg = '';
$msgClass = '';
//check for submit
if (filter_has_var(INPUT_POST, 'submit')) {
//GET FORM DATA
$name = htmlspecialchars($_POST['name']);
$email = htmlspecialchars($_POST['email']);
$message = htmlspecialchars($_POST['message']);
// check required fields
if (!empty($email) && !empty($name) && !empty($message)) {
// passed
// check email
if (filter_var($email, FILTER_VALIDATE_EMAIL) == false) {
//failed
$msg = 'Please use a valid email';
$msgClass = 'alert-danger';
} else{
//passed
// reciepient email
$toEmail = 'myemail#gmail.com';
$subject = 'Contact Request From '.$name;
$body = '<h2> Contact Request</h2>
<h4> Name </h4><p>'.$name.'</p>
<h4> Email </h4><p>'.$email.'</p>
<h4> Message </h4><p>'.$message.'</p>';
// email headers
$headers = "MIME-Version: 1.0"."\r\n";
$headers .= "Content-Type: text/html;charset=UTF-8" . "\r\n";
// additional headers
$headers .= "From:" .$name. "<".$email.">". "\r\n";
if (mail($toEmail, $subject, $body, $headers)) {
// email sent
$msg = ' Your email has been sent';
$msgClass = 'alert-success';
}
}
# code...
} else {
//failed
$msg = ' Please fill in all fields';
$msgClass = 'alert-danger';
// failed
# code...
}
# code...
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Contact Us</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container" >
<?php if ($msg != ''): ?>
<div class="alert <?php echo $msgClass; ?> "><?php echo $msg; ?></div>
<?php endif; ?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<div class="contact-form" >
<h1>Contact Us</h1>
<div class="txtb" >
<label>Name</label>
<input type="text"
name="name"
class="form-control"
value="<?php echo isset($_POST['name']) ? $name : ''; ?>">
</div>
<div class="txtb" >
<label>Email</label>
<input type="text"
name="email"
class="form-control"
value="<?php echo isset($_POST['email']) ? $email : ''; ?>" >
</div>
<div class="txtb" >
<label>Message</label>
<textarea name="message" class="form-control" ><?php echo isset($_POST['message']) ? $message : ''; ?></textarea>
</div>
<br>
<a type="submit" name="submit" class="btn" >Submit</a>
</form>
</div>
</body>
</html>
I don't know what type of the error you're seeing but there's a little thing to change
You need to change
<a type="submit" name="submit" class="btn" >Submit</a>
to
<input type="submit">

Not sure How to fix this issues about FILTER_VALIDATE_EMAIL

Please check my code. I have to 2 fields for validate email
one is
if ($email == NULL) {
$error['email'] = "email is missing";
}
another is
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$error['emailfilter'] = "email is Invalid";
}
But my Problem is when email field is blank/empty. I found those 2 warring is show. "email is missing" & "email is Invalid"; I want only one warring will show. Such as if email filed is blank/empty. It will show only "email is missing" not show me "email is Invalid" and when email is not valid It will show "email is Invalid". Below is my full code.
<?php
if (isset($_POST['contact'])) {
$warning = array();
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$msg = $_POST['message'];
$to = "asifurrahaman124#gmail.com";
$sub = "you got a msg";
$headers = "from: $email";
if ($firstname == NULL) {
$error['fname'] = "firstname is missing";
}
if($lastname == NULL){
$error['lname'] = "Last name is missing";
}
if ($email == NULL) {
$error['email'] = "email is missing";
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$error['emailfilter'] = "email is Invalid";
}
if ($msg == NULL) {
$error['msg'] = "message is required";
}
if (count( $error ) == 0) {
mail($to, $sub, $msg, $headers);
$success = "Message Submited";
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>conatact</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<form action="" method="POST">
<input type="text" name="firstname" Placeholder="First Name"><br />
<p class="error"><?php if (isset($error['fname'])) {
echo $error['fname'];
}?></p>
<input type="text" name="lastname" Placeholder="Last Name"><br />
<p class="error"><?php if (isset($error['lname'])) {
echo $error['lname'];
}?></p>
<input type="email" name="email" Placeholder="Email"><br />
<p class="error"><?php if (isset($error['email'])) {
echo $error['email'];
}?></p>
<p class="error"><?php if (isset($error['emailfilter'])) {
echo $error['emailfilter'];
}?></p>
<textarea name="message" cols="30" rows="10"></textarea><br />
<p class="error"><?php if (isset($error['msg'])) {
echo $error['msg'];
}?></p>
<input type="password" name="password" Placeholder="Password"><br />
<input type="submit" value="send" name="contact">
</form>
<h2 class="error"><?php if (isset($success)) {
echo $success;
}?></h2>
</body>
</html>
You want to use elseif for this, it will only trigger if the first condition isn't matched.
if ($email == NULL) {
$error['email'] = "email is missing";
} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$error['emailfilter'] = "email is Invalid";
}
This will check the first condition, do they have an email, if not it'll populate $error['email'], if the email has a value then it'll perform the filter_var on the email to check it's validity.

Contact Form not showing error messages or sending email

Before I get into it I would like to say that this did send emails from my local server so I have everything set up. After adding this form validation it no longer sends emails or shows errors. It just refreshes the page. I'm new to php coding so I'm sure I just have an if statement in the wrong order or something like that.
HTML
<section id="contact">
<h1 class="section-header">Contact Us Directly</h1>
<h4 class="text-center">Have any quesitons not answered in the <span>Questions Page</span>.</h4>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="POST">
<label for="fname">First Name</label>
<input type="text" id="fname" name="firstname" value="<?php $firstname ?>" placeholder="Your name.." tabindex="1" autofocus>
<span class="error"><?php $firstname_error ?></span>
<label for="lname">Last Name</label>
<input type="text" id="lname" name="lastname" value="<?php $lastname ?>" placeholder="Your last name.." tabindex="2">
<span class="error"><?php $lastname_error ?></span>
<label for="email">Email</label>
<input type="text" id="email" name="email" value="<?php $email ?>" placeholder="Your email.." tabindex="3">
<span class="error"><?php $email_error ?></span>
<label for="message">Message</label>
<textarea id="subject" name="message" value="<?php $message ?>" placeholder="Write something.." style="height:200px" tabindex="4"> </textarea>
<span class="error"><?php $message_error ?></span>
<input type="submit" value="Submit" tabindex="5">
<span class="success"><?php $success ?></span>
</form>
</section>
PHP
<?php
$firstname_error = $lastname_error = $email_error = $message_error = "";
$firstname = $lastname = $email = $message = $success = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["firstname"])) {
$firstname_error = "First name is required";
} else {
$firstname = test_input($_POST["firstname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$firstname)) {
$firstname_error = "Only letters and white space allowed";
}
}
if (empty($_POST["lastname"])) {
$lastname_error = "Last name is required";
} else {
$lastname = test_input($_POST["lastname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$lastname)) {
$lastname_error = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$email_error = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$email_error = "Invalid email format";
}
}
if (empty($_POST["message"])) {
$message = "";
} else {
$message = test_input($_POST["message"]);
}
if ($firstname_error == '' and $lastname_error == '' and $email_error == '' and $message_error == '' ){
$message_body = '';
unset($_POST['submit']);
foreach ($_POST as $key => $value){
$message_body .= "$key: $value\n";
}
$EmailFrom = localhost;
$EmailTo = "testrepairmail69#gmail.com";
$Subject = "New Order From tabletscreenfixer.com";
if (mail($EmailTo, $Subject, $message)){
$success = "Message sent, thank you for contacting us!";
$firstname = $lastname = $email = $message = '';
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
Your Code is begging for some improvements as #R Smith mentioned; nevertheless this version works; i have tested on my pc.
<?php
$firstname_error = $lastname_error = $email_error = $message_error = "";
$firstname = $lastname = $email = $message = $success = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["firstname"])) {
$firstname_error = "First name is required";
} else {
$firstname = test_input($_POST["firstname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$firstname)) {
$firstname_error = "Only letters and white space allowed";
}
}
if (empty($_POST["lastname"])) {
$lastname_error = "Last name is required";
} else {
$lastname = test_input($_POST["lastname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$lastname)) {
$lastname_error = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$email_error = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$email_error = "Invalid email format";
}
}
if (empty($_POST["message"])) {
$message = "";
} else {
$message = test_input($_POST["message"]);
}
if ($firstname_error == '' and $lastname_error == '' and $email_error == '' and $message_error == '' ){
$message_body = '';
unset($_POST['submit']);
// var_dump($_POST); exit();
foreach ($_POST as $key => $value){
$message_body .= "$key: $value\n";
}
$EmailFrom = "test#gamil.com";
$EmailTo = "tabletscreenfixer.com";//-> the message will be sent to this address if you have configure mail stuff well
$Subject = "New Order From tabletscreenfixer.com";
if (mail($EmailTo, $Subject, $message)){
$success = "Message sent, thank you for contacting us!";
$firstname = $lastname = $email = $message = '';
}else{
echo "Failure";
}
}else{
echo "Failure 2";
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<html>
<head>
<title>Test</title>
</head>
<body>
<section id="contact">
<h1 class="section-header">Contact Us Directly</h1>
<h4 class="text-center">Have any quesitons not answered in the <span>Questions Page</span>.</h4>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="POST">
<label for="fname">First Name</label>
<input type="text" id="fname" name="firstname" value="<?php echo $firstname ?>" placeholder="Your name.." tabindex="1" autofocus>
<span class="error"><?php echo $firstname_error ?></span>
<label for="lname">Last Name</label>
<input type="text" id="lname" name="lastname" value="<?php echo $lastname ?>" placeholder="Your last name.." tabindex="2">
<span class="error"><?php echo $lastname_error ?></span>
<label for="email">Email</label>
<input type="text" id="email" name="email" value="<?php echo $email ?>" placeholder="Your email.." tabindex="3">
<span class="error"><?php echo $email_error ?></span>
<label for="message">Message</label>
<textarea id="subject" name="message" value="<?php echo $message ?>" placeholder="Write something.." style="height:200px" tabindex="4"> </textarea>
<span class="error"><?php echo $message_error ?></span>
<input type="submit" value="Submit" tabindex="5">
<span class="success"><?php $success ?></span>
</form>
</section>
</body>
</html>
EDIT: Missing echo in the input value attribute;
Hope it helps;
Add some debugging. For example, everywhere you have an error, increment a error counter. Something like this:
if (empty($_POST["email"])) {
$email_error = "Email is required";
$errors++;
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$email_error = "Invalid email format";
}
}
Then, at the end, instead of the long if condition:
if ($firstname_error == '' and $lastname_error == '' and $email_error == '' and $message_error == '' ){
You can use something like:
if ($errors == 0){
Which indicates no errors. Then, inside that if, when you try to send the mail, check for failure:
if (mail($EmailTo, $Subject, $message)){
$success = "Message sent, thank you for contacting us!";
$firstname = $lastname = $email = $message = '';
}
else {
echo "The mail command failed!!";
}
Finally, give yourself some sort of indicator that there were errors, just for your testing phase. You can remove this else (or even add better styling and keep it):
if ($errors == 0){
// snip - lines of code in here removed to keep this snippet readable. this is your test and send mail logic.
}
else {
echo "You've got $errors errors! You need to correct them!";
}
With these changes, you should be able to find your issues quickly. As I said, you can also remove some of this code (like the echo statements) once you've finished your debugging.
Good luck!

PHP email form validating doesn

I'm kinda new in PHP and I've created a form that should validate data and submit an error if any field is blank or incorrect. It doesn't tho. Even if email is wrong or any field is empty and the errors are shown it still sends an email. And the headers are not showing in the message. The only case when the errors are shown and the mail isn't send is the case when all fields are empty. Here's the code:
<?php
$NameErr = $EmailErr = $SubErr = $MessErr = "";
$Name = $Email = $Subject = $Message = "";
$header = "From: " . $Email . "Name: " . $Name . "\r\n";
$header .= "Content-Type: text/plain";
$To = "xxx#gmail.com";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["Name"])) {
$NameErr = "Name is required";
} else {
$Name = test_input($_POST["Name"]);
if (!preg_match("/^[a-zA-Z ]*$/", $Name)) {
$NameErr = "Only letters and white space allowed!";
}
}
if (empty($_POST["Email"])) {
$EmailErr = "Email is required";
} else {
$Email = test_input($_POST["Email"]);
if (!filter_var($Email, FILTER_VALIDATE_EMAIL)) {
$EmailErr = "Invalid email format";
}
}
if (empty($_POST["Subject"])) {
$SubErr = "Subject is required";
} else {
$Subject = test_input($_POST["Subject"]);
}
if (empty($_POST["Message"])) {
$MessErr = "Message is required";
} else {
$Message = test_input($_POST["Message"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
<p><input class="w3-input w3-padding-16" type="text" placeholder="Name" name="Name"></p>
<span class="error"> <?php echo $NameErr; ?></span>
<p><input class="w3-input w3-padding-16" type="text" placeholder="Email" name="Email"></p>
<span class="error"> <?php echo $EmailErr; ?></span>
<p><input class="w3-input w3-padding-16" type="text" placeholder="Subject" name="Subject"></p>
<span class="error"> <?php echo $SubErr; ?></span>
<p><input class="w3-input w3-padding-16" type="text" placeholder="Message" name="Message"></p>
<span class="error"> <?php echo $MessErr; ?></span>
<p>
<button class="w3-btn w3-grey w3-padding-large w3-hover-green" type="submit" value="Submit" name="pressed">
<i class="fa fa-paper-plane"></i> SEND MESSAGE
</button>
</p>
</form>
<?php
if (isset($_POST["pressed"])) {
if (empty($NameErr && $SubErr && $MessErr && $EmailErr)) {
mail($To, $Subject, $Message, $header);
echo "Email sent.";
} else {
echo "Error.";
}
}
?>
Can you help me? Error validating is on and it doesn't show me any errors.
use isset function instead of empty() to check if the field is posted or not.
example:
if (!isset($_POST["Name"])) {
...
also there is no need to check the request method, $_POST will only catch post requests.
So I've re designed the code structure for you. Generally calling a class and a function will keep your files and your code cleaner.
So with this being said, let me show you some insight. This is where your form will be located for example: form.php
<?php
require ('mail.php');
$send = new Mail();
if (isset($_POST['sendIt']))
{
$send->sendMail($_POST['nameP'], $_POST['email'], $_POST['subject'], $_POST['message']); // Call the class and function
}
?>
<form id="contact" method="post">
<div class="container">
<input type="text" name="nameP" placeholder="Name *" /><br />
<input type="email" name="email" placeholder="Email *"/><br />
<input type="text" name="subject" placeholder="Subject *"><br />
<textarea name="message" id="" cols="30" rows="10"></textarea>
<input type="submit" name="sendIt" id="submit">
</div>
</form>
Then create yourself a mail.php file to store the class and the functions revolving around mailing in general:
<?php
class Mail
{
public function sendMail($name, $email, $subject, $message)
{
if (!empty($name))
{
if (!empty($email))
{
if (!empty($subject))
{
if (!empty($message))
{
$email_to = 'Your#emailAddress';
$header = 'From: ' . $name ."<noreply#youremail>". "\r\n" .
'Reply-To: ' . $email . "\r\n" .
'X-Mailer: PHP/' . phpversion();
#mail($email_to, 'Enquiry Received', 'Name: ' . $name . "\r\n\r\n". 'Email Address: ' .$email."\r\n\r\n" . 'Message: ' .$message."\r\n\r\n". $header);
echo "SUCCESS MESSAGE";
} else {
echo "Please fill in your message";
}
} else {
echo "Please provide a subject.";
}
} else {
echo "Please provide your email address.";
}
} else {
echo "Please provide your name.";
}
}
}
?>
This will generally clear the form if there is an error by default however you can then simply add value="<?php echo $_POST['whateverThisFormIsFor'];?>
I hope this will help and give you some further insight.
The way you're constructing your empty check towards the bottom is incorrect:
if (empty($NameErr && $SubErr && $MessErr && $EmailErr)){
The only way that this will evaluate to false is if all of the error messages are set, and the above snippet will break before PHP 5.5 (as Felippe mentioned in the comments). What you want instead is the below; it returns true only if none of the error messages are set:
if (empty($NameErr)
&& empty($SubErr)
&& empty($MessErr)
&& empty($EmailErr)) {
Another way to do this would be to
extract the validation logic into methods for readability,
read off of an $errors array instead of $NameErr, $SubjectErr, etc.
keep POST logic together (instead of split between the beginning and end)
To those ends, I've rewritten your snippet below:
<?php
function validateName($input)
{
if (empty($input)) {
return 'Name is required';
}
if (preg_match("/^[a-zA-Z ]*$/", $input) != 1) {
return 'Name may only contain letters and spaces';
}
return null;
}
function validateEmail($input)
{
if (empty($input)) {
return 'Email is required';
}
if (filter_var($input, FILTER_VALIDATE_EMAIL)) {
return 'Email is in an invalid format';
}
return null;
}
function validateSubject($input)
{
return empty($input) ? 'Subject is required' : null;
}
function validateMessage($input)
{
return empty($input) ? 'Message is required' : null;
}
function test_input($data)
{
return htmlspecialchars(stripslashes(trim($data)));
}
$errors = [];
$notification = '';
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = test_input($_POST['name'] ?: '');
$email = test_input($_POST['email'] ?: '');
$subject = test_input($_POST['subject'] ?: '');
$message = test_input($_POST['message'] ?: '');
if (($error = validateName($name)) !== null) {
$errors['name'] = $error;
}
if (($error = validateEmail($email)) !== null) {
$errors['email'] = $error;
}
if (($error = validateSubject($subject)) !== null) {
$errors['subject'] = $error;
}
if (($error = validateMessage($message)) !== null) {
$errors['message'] = $error;
}
if (empty($errors)) {
$headers = [
"From: $name <$email>",
"Content-Type: text/plain",
];
$to = "xxx#gmail.com";
mail($to, $subject, $message, implode("\r\n", $headers));
$notification = 'The email was sent!';
} else {
$notification = 'The email could not be sent; please check below for errors.';
}
}
?>
<form method="post" action="<?= htmlspecialchars($_SERVER['PHP_SELF']) ?>">
<?php if (!empty($notification)): ?><p><?= $notification ?></p><?php endif; ?>
<p><input class="w3-input w3-padding-16" type="text" placeholder="Name" name="name" required></p>
<?php if (isset($errors['name'])): ?><span class="error"> <?= $errors['name'] ?></span><?php endif; ?>
<p><input class="w3-input w3-padding-16" type="email" placeholder="Email" name="email" required></p>
<?php if (isset($errors['email'])): ?><span class="error"> <?= $errors['email'] ?></span><?php endif; ?>
<p><input class="w3-input w3-padding-16" type="text" placeholder="Subject" name="subject" required></p>
<?php if (isset($errors['subject'])): ?><span class="error"> <?= $errors['subject'] ?></span><?php endif; ?>
<p><input class="w3-input w3-padding-16" type="text" placeholder="Message" name="message" required></p>
<?php if (isset($errors['message'])): ?><span class="error"> <?= $errors['message'] ?></span><?php endif; ?>
<p>
<button class="w3-btn w3-grey w3-padding-large w3-hover-green" type="submit">
<i class="fa fa-paper-plane"></i> SEND MESSAGE
</button>
</p>
</form>

Check if email address exist in database and captcha code is correct if not give alert and dont save data in database

i wrote a code for a form in which i added a two validation first one is through email and second one is through email. when user enter's the email address which already exist in a data base it will show an error. the problem which i faced is that when user enter's a new email address and wrong captcha code than it will show an error but at the same time it will save that into the data base also. Here's the complete code is given
<?php
include('../config/connection.php');
//DATABASE INSERT QUERY
if(isset($_POST['submit']))
{
$finame = $_POST['finame'];
$email = $_POST['email'];
$user_message = $_POST['message'];
$b="SELECT * from form WHERE email='".$_POST['email']."'";
$res = mysql_query($b);
$tot = mysql_fetch_assoc($res);
if(empty($tot) || empty($_SESSION['6_letters_code'] ) ||
strcasecmp($_SESSION['6_letters_code'], $_POST['6_letters_code']) == 0)
{
$sel = "insert into ".form." set finam='".$_POST['finam']."',lnam='".$_POST['lnam']."',dob='".$_POST['dob']."',cntn='".$_POST['cntn']."',fanam='".$_POST['fanam']."',str='".$_POST['str']."',email='".$_POST['email']."',passw='".$_POST['passw']."'";
mysql_query($sel);
}
//-------------------------------Captcha--------------------
$your_email ='yourname#your-website.com';// <<=== update to your email address
session_start();
$errors = '';
$finame = '';
$email = '';
$user_message = '';
///------------Do Validations-------------
if(!empty($tot))
{
$errors .= "\n Re-enter the captcha code...!!! ";
$msg .="Email adreess already exist";
}
if(IsInjected($email))
{
$errors .= "\n Bad email value!";
}
if(empty($_SESSION['6_letters_code'] ) ||
strcasecmp($_SESSION['6_letters_code'], $_POST['6_letters_code']) != 0)
{
// strcmp()
$errors .= "\n The captcha code does not match!";
}
if(empty($errors))
{
//send the email
$to = $your_email;
$subject="New form submission";
$from = $your_email;
$ip = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '';
$body = "A user $name submitted the contact form:\n".
"Name: $finame\n".
"Email: $email \n".
"Message: \n ".
"$user_message\n".
"IP: $ip\n";
$headers = "From: $from \r\n";
$headers .= "Reply-To: $visitor_email \r\n";
mail($to, $subject, $body,$headers);
header('Location: ../admin/sign-in1.php');
}
}
// Function to validate against any email injection attempts
function IsInjected($str)
{
$injections = array('(\n+)',
'(\r+)',
'(\t+)',
'(%0A+)',
'(%0D+)',
'(%08+)',
'(%09+)'
);
$inject = join('|', $injections);
$inject = "/$inject/i";
if(preg_match($inject,$str))
{
return true;
}
else
{
return false;
}
}
?>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="jsDatePick_ltr.min.css" />
<script type="text/javascript" src="jsDatePick.min.1.3.js"></script>
<script type="text/javascript">
window.onload = function(){
new JsDatePick({
useMode:2,
target:"inputField",
dateFormat:"%d-%M-%Y"
});
};
</script>
<title>Form</title>
<link href="style/style.css" rel="stylesheet" type="text/css">
<link href='http://fonts.googleapis.com/css?family=Kaushan+Script' rel='stylesheet' type='text/css'>
<script language="JavaScript" src="scripts/gen_validatorv31.js" type="text/javascript"></script>
</head>
<body>
<div style="width:100%; height:170px; margin:auto;">
<div class="abc">
<h1 style="margin:5% 0 0 5%; width:10%; color:#FFF;">Form</h1>
<!--</form>-->
<?php
$sel = "select * from home";
$a=mysql_query($sel);
$fetch = mysql_fetch_array($a);
?>
<div class="sample"> <?php echo $fetch['home4'];?></div>
<div class="main" style="margin:4% 0 0 0;">
Home
About us
Gallery
Contact us
</div>
</div>
</div>
<div style=" width:100%; margin:5% 0 0 0; height:auto;">
<div style="margin:auto; width:80%">
<form method="post" class="w3-container" onSubmit="alert('Thank you. You are registered now input your login id and passwprd to make changes on index and another pages...')" >
<div class="w3-group">
<input class="w3-input blue-l4" pattern="[A-Za-z]{3,}" title="only alphabets" value="<?php echo $_POST['finam'] ?>" type="text" name="finam"required>
<label class="w3-label">First-Name</label>
</div>
<div class="w3-group">
<input class="w3-input blue-l4" pattern="[A-Za-z]{3,}" title="only alphabets" value="<?php echo $_POST['lnam'] ?>" type="text" name="lnam"required>
<label class="w3-label">Last name</label>
</div>
<div class="w3-group">
<input class="w3-input blue-l4" type="text" size="12" readonly id="inputField" value="<?php echo $_POST['dob'] ?>" name="dob" placeholder="DD/MM/YY"required>
</div>
<div class="w3-group">
<input class="w3-input blue-l4" type="text" pattern="[A-Za-z]{3,}" title="only alphabets" value="<?php echo $_POST['fanam'] ?>" name="fanam"required>
<label class="w3-label">Father's name</label>
</div>
<div class="w3-group">
<?php
if(!empty($msg)){
echo "<p class='err'>".nl2br($msg)."</p>";
}
?>
<input class="w3-input blue-l4" value="<?php echo $_POST['email'] ?>" type="email" name="email"required>
<label class="w3-label">Email</label>
</div>
<div class="w3-group">
<input class="w3-input blue-l4" type="password" name="passw" required>
<label class="w3-label">Password</label>
</div>
<div class="w3-group">
<input class="w3-input blue-l4" pattern="[0-9]+" value="<?php echo $_POST['cntn'] ?>" title="only numeric value" type="text" name="cntn"required>
<label class="w3-label">Contact no.</label>
</div>
<div class="clear"></div>
<div class="w3-group">
<select name="str" class="w3-input blue-l4">
<option>--Select Stream--</option>
<?php
$sel = "select * from stream";
$a=mysql_query($sel);
while($fetch = mysql_fetch_array($a))
{
?>
<option><?php echo $fetch['str']?></option>
<?php
}
?>
</select>
</div>
<div class="w3-group">
<?php
if(!empty($errors)){
echo "<p class='err'>".nl2br($errors)."</p>";
}
?>
<img src="captcha_code_file.php?rand=<?php echo rand(); ?>" id='captchaimg' ><br>
<label for='message'>Enter the code above here :</label><br>
<input class="w3-input blue-l4" id="6_letters_code" name="6_letters_code" type="text"><br>
<small>Can't read the image? click <a href='javascript: refreshCaptcha();'>here</a> to refresh</small> </div>
<button class="w3-btn blue-d1" name="submit" value="submit">Submit</button>
</form>
</div>
</div>
<script language='JavaScript' type='text/javascript'>
function refreshCaptcha()
{
var img = document.images['captchaimg'];
img.src = img.src.substring(0,img.src.lastIndexOf("?"))+"?rand="+Math.random()*1000;
}
</script>
<div class="foot" style="margin-top:4px;">
<div style="margin:2% 0 2% 86%;">
<img style="margin:0 0 12px 12px;" src="index.jpg" width="30" height="30"/>
<img style="margin:0 0 12px 12px;" src="images1.png" width="30" height="30"/>
<img src="googleplus.png" width="50" height="50"/>
</div>
</div>
</div>
</body>
</html>
Several comments here. First, and maybe the most important, you're using mysql_* functions, which are deprecated and is no longer maintained. You should seriously consider converting to MySQLi or PDO, which has prepared statements (that protects you against SQL-inection). mysql_* is bad practice.
Furthermore, you are mixing variable-names in your code. You're using both $_POST['finam'] and $_POST['finame'], which I assume are one and the same. Be careful with your names!
And you're inserting the password in plain text -- this is also a security issue! You should really hash your password, so that it's never stored in plain text (in case of a hacker accessing your database).
As for your question: You are inserting into the database with a series of or-operators in your if-statement. This means as long as one of them returns TRUE, it'll run the query and insert the email.
I'm not really sure how you do your CAPTCHA-validating, but I think this code will work more as intended.
<?php
session_start();
include('../config/connection.php');
//DATABASE INSERT QUERY
if (isset($_POST['submit'])) {
$finame = $_POST['finam'];
$lname = $_POST['lnam'];
$dob = $_POST['dob'];
$passw = $_POST['passw'];
$email = $_POST['email'];
$fanam = $_POST['fanam'];
$cntn = $_POST['cntn'];
$user_message = $_POST['message'];
$str = $_POST['str'];
$errors = '';
///------------Do Validations-------------
// Checking if the email exists in the database
$res = mysql_query("SELECT * FROM form WHERE email=$email");
// If the number of rows from the result is greater than 0, the email is already in our database
if (mysql_num_rows($res) > 0) {
$errors .= "\n Email exists!";
$emailAvailable = false;
} else {
$emailAvailable = true;
}
if (!$emailAvailable)) {
$errors .= "\n Re-enter the captcha code...!!! ";
$msg .= "Email adreess already exist";
}
if (IsInjected($email)) {
$errors .= "\n Bad email value!";
$badEmail = false;
} else {
$badEmail = true;
}
if (empty($_SESSION['6_letters_code'] ) || strcasecmp($_SESSION['6_letters_code'], $_POST['6_letters_code']) != 0) {
// strcmp()
$errors .= "\n The captcha code does not match!";
$captcha = false;
} else {
$captcha = true;
}
///------------If all is well, inserting the email-------------
if ($emailAvailable && $captcha && $badEmail) {
// $sel = "insert into ".form." set finam='".$_POST['finam']."',lnam='".$_POST['lnam']."',dob='".$_POST['dob']."',cntn='".$_POST['cntn']."',fanam='".$_POST['fanam']."',str='".$_POST['str']."',email='".$_POST['email']."',passw='".$_POST['passw']."'";
$sel = "INSERT INTO form (finam, lnam, dob, cntn, fanam, str, email, passw) VALUES ($finame, $lname, $dob, $cntn, $fanam, $str, $email, $passw)";
mysql_query($sel);
}
//-------------------------------Captcha--------------------
$your_email ='yourname#your-website.com';// <<=== update to your email address
if(empty($errors)) {
//send the email
$to = $your_email;
$subject = "New form submission";
$from = $your_email;
$ip = $_SERVER['REMOTE_ADDR'];
$body = "A user $name submitted the contact form:\n".
"Name: $finame\n".
"Email: $email \n".
"Message: \n ".
"$user_message\n".
"IP: $ip\n";
$headers = "From: $from \r\n";
$headers .= "Reply-To: $visitor_email \r\n";
mail($to, $subject, $body,$headers);
header('Location: ../admin/sign-in1.php');
}
}
// Function to validate against any email injection attempts
function IsInjected($str) {
$injections = array('(\n+)',
'(\r+)',
'(\t+)',
'(%0A+)',
'(%0D+)',
'(%08+)',
'(%09+)'
);
$inject = join('|', $injections);
$inject = "/$inject/i";
if (preg_match($inject,$str)) {
return true;
} else {
return false;
}
}
?>
As you can see, I also updated your INSERT-query, it was kind of messy.

Categories