Form Validation (PHP) - php

I need to create validation for this form, and I don't know how to do it right.
<?php
$errName = '';
$errEmail = '';
$errMessage = '';
$result = '';
if (isset($_POST["submit"])) {
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$from = 'simply#email.tld';
$to = 'again#email.tld';
$subject = 'Form';
$body = "Name: $name \n E-mail: $email \n Message: $message";
}
if (!$_POST['name']) {
$errName = 'Write Name here.';
}
if (!$_POST['email'] || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$errEmail = 'Write correct e-mail';
}
if (!$_POST['message']) {
$errMessage = 'Write your message';
}
if (!$errName && !$errEmail && !$errMessage) {
if (mail ($to, $subject, $body, $from)) {
$result = "<div style='color:white;font-size:15px;font-weight:700;'>Your message has been sent.</div>";
} else {
$result = "<div style='color:red;font-size:15px;font-weight:700;'>Your message has not been sent, try again!</div>";
}
}
?>
The form works right but if as example I won't write one thing there is no error, message just isn't sent. Any ideas what's wrong?

The problem I see with your original code is that the variables that contain the error message ($errName, $errEmail, $errMessage) aren't ever echo'd anywhere. They simply get checked if they contain any content and if none of them do then the mail function is called, otherwise nothing.
I believe a better approach to this would be to use a try/catch block. Your approach continues checking for valid variables even if a previous variable has already failed a check and the mail is already going to be prevented because of it. In this application, a couple extra easy checks aren't going to amount to anything significant, resource-wise. But in a larger application it's a good idea to not waste resources if you already know something is going to fail.
I've rewritten your code using the suggested try/catch block.
<?php
if (isset($_POST["submit"])) {
$name = (string) $_POST['name'];
$email = (string) $_POST['email'];
$message = (string) $_POST['message'];
$from = 'simply#email.tld';
$to = 'again#email.tld';
$subject = 'Form';
$body = "Name: $name \n E-mail: $email \n Message: $message";
try {
if (!$name) {
throw new Exception('Write Name here.');
}
if (!$email || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
throw new Exception('Write correct e-mail');
}
if (!$message) {
throw new Exception('Write your message');
}
if (mail ($to, $subject, $body, $from)) {
$result = "<div style='color:white;font-size:15px;font-weight:700;'>Your message has been sent.</div>";
} else {
throw new Exception("Your message has not been sent, try again!");
}
} catch(Exception $e){
$result = "<div style='color:red;font-size:15px;font-weight:700;'>" . $e->getMessage() . "</div>";
}
echo $result;
}
?>
If a variable doesn't pass one of your checks, a new Exception is thrown with the applicable error message. This stops further execution in the try block and moves execution to the catch block. The $result variable gets filled with your styled error message, which gets echo'd at the end. Likewise, if the mail is successfully sent, the $result variable gets filled with the success message which gets echo'd.

Related

PHP Captcha showing error message even when captcha is enter correctly

I have created a contact form that once the user enters their details and clicks submit the details they have entered are sent to my email. The form works well and the emails are being sent, however I noticed that I would receive a lot of spam emails from the contact form. I decided that the best way to stop the the spam would be to add a captcha so that the user must enter the letters within the captcha image before the form can be submitted.
I have been able to get the captcha image to display, however even if the captcha is not entered correctly the form still seems to submit.
Here is my contact form code
<?php
if (isset($_POST["submit"])) {
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$captcha = $_POST['captcha-input'];
$from= 'From:' . $name . "\r\n" .'Reply-To:' . $email . "\r\n" .'X-Mailer: PHP/' . phpversion();
$to = 'example#yahoo.com';
$subject = 'Message from example.com';
$body = "$message";
if (!$_POST['name']) {
$errorName = 'Please enter your name';
}
if (!$_POST['email'] || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$errorEmail = 'Please enter a valid email address';
}
if (!$_POST['message']) {
$errorMessage = 'Please enter your message';
}
if (!$_POST['captcha-input'] || filter_var($_POST['captcha-input'], FILTER_SANITIZE_STRING)) {
$errorCaptcha = 'Please enter the captcha';
}
if ($_SESSION['CAPTCHA_CODE'] !== $captchaUser) {
$result = '<div id="error" class="error">CAPTCHA has failed</div>';
} else if (!$errorName && !$errorEmail && !$errorMessage) {
if (mail ($to, $subject, $body, $from)) {
$result='<div id="success" class="success">Thank You! I will be in touch</div>';
} else {
$result='<div class="error">Sorry there was an error sending your message. </div>';
}
$_POST = array();
}
}
What I can see is, you have an mistake in your variable name. In this line:
$captcha = $_POST['captcha-input'];
You were reading the captcha entered by the user to the $captcha variable.
But here:
if ($_SESSION['CAPTCHA_CODE'] !== $captchaUser) {
You are using the wrong variable name for comparison!
It should be this:
if ($_SESSION['CAPTCHA_CODE'] !== $captcha) {
EDIT
I am assuming that, you are setting the catpcha after that main IF condition (before the display takes place) :
<?php
// for session
session_start();
if (isset($_POST["submit"])) {
//... all your code goes here..
}
// generate the captcha code and store it in session
$_SESSION['CAPTCHA_CODE'] = 'new_captcha_code_generated';
Also, one more thing I noticed that, you are not calling the session_start() function. Please make sure that you call this function at the very start of your PHP code, in all pages. Then only the SESSION would work properly! Reference: https://www.php.net/manual/en/function.session-start.php
It looks like you're using a variable that is never initialised, in the line:
if ($_SESSION['CAPTCHA_CODE'] !== $captchaUser)
You're using the $captchaUser variable which is never created, perhaps you mean the $captcha variable you initialise toward the top of your page?

php code not rendering bootstrap alert

I'm fairly new to coding and have been struggling to get my contact_process.php form to display an alert message when the contact form's name or email is filled out incorrectly. For some reason, my .alert .alert-danger class does not display, but my .alert .alert-success class does after my form is submitted. I'm storing the results of my if else statement in the variable result and using echo to display it. Any help would be most appreciated.
Here's my code:
<?php
// isset function checks if the variable is set or has a value
if (isset($_POST['submit'])) {
// Declaring the variables
$name = $_POST['name'];
$email = $_POST['email'];
$date = $_POST['date'];
$message = $_POST['message'];
$from = 'Business Name';
$to = 'byron#gmail.com';
$subject = 'New Contact';
// Fills the content of the email
$body = "From: $name\n Email: $email\n DOB: $date\n Message:\n $message";
// Checks that the user entered a name
if (!$_POST['name']) {
$errorName = 'Enter your first and last name please';
}
// Checks if the user entered a valid email address
if (!$_POST['email'] || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$errorEmail = 'Only valid email addresses please';
}
// Function checks for errors, if there are none, it sends the form
if (!$errorName && !$errorEmail) {
if (mail ($to, $subject, $body, $from)) {
$result='<div class="alert alert-success" role="alert">Thank you for contacting our business.<br>We will contact you soon.</div>';
}
else {
$result='<div class="alert alert-danger" role="alert">Sorry your message was unsuccessful.<br>Please try again by returning to the contact page.</div>';
}
}
}
?>
<?php include 'header.php'; ?>
<main>
<!-- Echo prints the result of the form being sent or not -->
<?php echo $result; ?>
</main>
<?php include 'footer.php'; ?>

PHP mail() not receiving the email [duplicate]

This question already has answers here:
PHP mail function doesn't complete sending of e-mail
(31 answers)
Closed 6 years ago.
I'm trying to set up a contact me page and currently I've got it working all the way to the point of the 'message sent' result showing up correctly. However the e-mail never shows up for me in my box inbox.
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
$antispam = $_POST['antispam'];
$to = 'myemailaddress#gmail.com';
$from = 'From : ' . $email;
$body = "From: $name\n E-Mail: $email\n Message:\n $message";
if ($antispam == '10' || 'Ten' || 'ten') {
$human = true;
}
if($_POST['submit'] && $name != "" && $email != "" && $message != "" && $subject != "") {
if ($human == true) {
if (mail($to, $subject, $body, $from)) {
$result = "Your message was sent successfully!";
} else {
$result = "Something went wrong! Try sending your message again";
}
} else {
$result = "You answered the anti-spam answer incorrectly. Please try again.";
}
} else {
$result = "You did not fill out a required field. Please try again.";
}
?>
<?php echo $result; ?>
I've read seperately that Gmail has issues with PHP mail(), is that possibly the cause?
I found the answer and honestly feel dumber for not recognizing it.
It was never told to send the email, just check if sending it would be true or not. I know that sounds weird but here's the old code:
if ($human == true) {
if (mail($to, $subject, $body, $from)) {
$result = "Your message was sent successfully!";
} else {
$result = "Something went wrong! Try sending your message again";
}
and here's the fixed version
if ($human == true) {
mail($to, $subject, $body, $from);
if (mail($to, $subject, $body, $from)) {
$result = "Your message was sent successfully!";
} else {
$result = "Something went wrong! Try sending your message again";
}
to be short, I added mail($to, $subject, $body, $from); after the check to see if $human == true

Redirect to another page after successfully submit the form

I've found a template that I want to edit and it already has a nice looking contact form. After hitting the submit button I'm getting a thank you message but I would like to redirect to another page where the message will appear so I can use it for conversion tracking.
Could someone be of assistance what should I do as my current code looks like this:
<?php
$firstname = '';
$number = '';
$message = '';
$email = '';
if($_POST) {
// collect all input and trim to remove leading and trailing whitespaces
$firstname = trim($_POST['first_name']);
$number = trim($_POST['phone']);
$message = trim($_POST['message']);
$email = trim($_POST['email']);
$errors = array();
// Validate the input
if (strlen($firstname) == 0)
array_push($errors, "Please enter your name");
if (strlen($number) == 0)
array_push($errors, "Please specify your number");
if (strlen($message) == 0)
array_push($errors, "Please enter the details of your message");
if (!filter_var($email, FILTER_VALIDATE_EMAIL))
array_push($errors, "Please specify a valid email address");
// If no errors were found, proceed with storing the user input
if (count($errors) == 0) {
//completion message into array
$to = 'me#mymailzz.com'; // note the comma
// the email subject ( modify it as you wish )
$subject = "Enquiry From website";
// the mail message ( add any additional information if you want )
$msg = "Quote From website:\n-------------------------------------------\n Name: $firstname \n Number: $number \n Email: $email \n Message: $message \n-------------------------------------------";
//function to send email
try {
mail($to, $subject, $msg, "From: $email\r\nReply-To: $email\r\nReturn-Path: $email\r\n");
$return1 = "Thank You for sending your message, we will be in touch within 48-72 hours";
array_push($errors, $return1);
$formsubmit = 1;
}catch(Exception $e){
$return3 = "<center><p><b>Your message did not get sent due to an error. Please try again. Caught Exception {$e->getMessage()}</center>";
array_push($errors, $return3);
$formsubmit = 0;
}
}
//Prepare errors for output
$output = '';
foreach($errors as $val) {
$output .= "<p class='output'>$val</p>";
}
}
?>
Replace the line:
$return1 = "Thank You for sending your message, we will be in touch within 48-72 hours";
With something like this:
header('Location: some_page.php');
exit;
And then you can remove these lines as they become obsolete:
array_push($errors, $return1);
$formsubmit = 1;
That will redirect to some_page.php instead of printing that message.
To store the message across pages, do this at the start of your script:
session_start();
Instead of storing messages in a normal variable, store it in a session variable, e.g.:
$_SESSION['message'] = 'Your message here';
At the end of your script:
if ($formsubmit == 1) {
header('Location: your-file.php');
}
In your-file.php:
<?php
session_start();
echo $_SESSION['message'];
Just made a change in your try code and insert redirect fuunction
try {
mail($to, $subject, $msg, "From: $email\r\nReply-To: $email\r\nReturn-Path: $email\r\n");
echo ("<SCRIPT LANGUAGE='JavaScript'>
window.location.href='next_page.php'
</SCRIPT>");
}
How about you trace in your web template where you have <form action="#"> and proceed with help from a previously similar asked question found here

PHP form redirect (header) in external php file not working

I have a form on my homepage, which when submitted runs an external form.php file containing the code below. I am testing on MAMP and the header redirect doesn't seem to be working the url is just stuck on the form.php url? I have previously had an echo function which worked fine!? What am I doing wrong? Please help, many thanks in advance
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$company = $_POST['company'];
$robots = $_POST['robots'];
$from = 'From: Blah Register Form';
$to = 'sofi.smith#blah.com';
$subject = 'Blah Lead';
$body = "From: $name\n E-Mail: $email\n company: $company\n ";
if ($_POST['submit'] && $robots == '') {
if (mail ($to, $subject, $body, $from)) {
header("Location: http://google.com");
exit;
}
else {
echo '<p>Something went wrong, please try again</p>';
}
}
else if ($_POST['submit'] && $robots != '') {
echo 'Sorry, we don\'t like spammers here!';
}
?>
I can see a space before the first php tag, and you shouldn't close php tags either. That space means that content is sent before header.
However, your header statement can be failing due to several reasons (headers already sent, warning, etc). One quick dirty workaround is to use javascript for that matter:
if (mail ($to, $subject, $body, $from)) {
echo '<script>location.href="http://www.google.com";</script>';
exit;
}
You're condition will not always resolve to true in both scenarios. So unless you know for sure that the email is being sent, you don't know if any of the code is being called. This tightens it's up a bit:
if($_POST['submit']) {
if ($robots == '') {
if (mail($to, $subject, $body, $from)) {
header("Location: http://google.com");
} else {
echo 'Something went wrong, please try again';
}
} else {
echo 'Sorry, we don\'t like spammers here!';
}
} else {
echo "submit was not set";
}
Because right now you have:
if ($_POST['submit'] && $robots == '') {
// send the email or whatever
} else if ($_POST['submit'] && $robots != '') {
echo 'Sorry, we don\'t like spammers here!';
}
which means that if $_POST['submit'] is not set, neither condition would be true.
First of all write error_reporting(E_ALL); then you can see the exact error on page.
Also as i can see mail function it should be mail( $to , $subject , $message, $additional_headers )
I guess there is error in mail function thats why the header function is not working
Hope this works:
<?php
if($_POST) {
$name = mysql_real_escape_string(strip_tags($_POST['name']));
$email = mysql_real_escape_string(strip_tags($_POST['email']));
$company = mysql_real_escape_string(strip_tags($_POST['company']));
$robots = mysql_real_escape_string(strip_tags($_POST['robots']));
$from = 'From: Blah Register Form';
$to = 'sofi.smith#blah.com';
$subject = 'Blah Lead';
$body = "From: $name\n E-Mail: $email\n company: $company\n ";
if($robots == '') {
$mail = mail($to, $subject, $body, $from);
if($mail) {
header('Location: http://google.com');
exit();
} else {
echo '<p>Something went wrong, please try again</p>';
}
} else if($robost != '') {
echo 'Sorry, we don\'t like spammers here!';
}
}
?>

Categories