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'; ?>
Related
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
if (isset($_POST["sendMessage"])) {
$firstName = $_POST['firstName'];
$lastName = $_POST['last-name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];
$from= 'info#address.com';
$to = 'some#gmail.com';
$subject = 'Message from Contact Demo ';
$txt= 'demo';
$headers = "From: webmaster#example.com" . "\r\n" .
"CC: somebodyelse#example.com";
$body = "From: First-Name: $firstName\n Last-Name: $lastName\n
E-Mail: $email\n Phone: $phone\n Message: $message";
$errFirstName='';$errLastName='';$errEmail='';$errPhone='';$errMessage='';
// If there are no errors, send the email
if (mail ($to, $subject,$txt,$headers)) {
$result='<div class="alert alert-success">Thank You! I will be in touch</div>';
} else {
$result='<div class="alert alert-danger">Sorry there was an error sending your message. Please try again later</div>';
}
}
?>
i am trying to make a mail validation but it will not work.Here some text which will give a success message or error message.but it show nothing . i can't understand my fault. please help someone.
Try this code on your live server
$firstName = "sunny";
$lastName = "khatri";
$email = '******#gmail.com';
$phone = '********';
$message ='Hello this is test';
$from= '*****#gmail.com';
$to = '***#gmail.com';
$subject = 'Message from Contact Demo ';
$txt= 'demo';
$headers = "From: ******#*****.com" . "\r\n" .
"CC: ********#live.in";
$body = "From: First-Name: $firstName\n Last-Name: $lastName\n
E-Mail: $email\n Phone: $phone\n Message: $message";
$errFirstName='';$errLastName='';$errEmail='';$errPhone='';$errMessage='';
// If there are no errors, send the email
if (mail ($to, $subject,$txt,$headers)) {
$result='<div class="alert alert-success">Thank You! I will be in touch</div>';
} else {
$result='<div class="alert alert-danger">Sorry there was an error sending your message. Please try again later</div>';
}
echo $result;
Just use default function from PHP manual:
<?php
$email_a = 'joe#example.com';
$email_b = 'bogus';
if (filter_var($email_a, FILTER_VALIDATE_EMAIL)) {
echo "This ($email_a) email address is considered valid.\n";
}
if (filter_var($email_b, FILTER_VALIDATE_EMAIL)) {
echo "This ($email_b) email address is considered valid.\n";
} else {
echo "This ($email_b) email address is considered invalid.\n";
}
?>
First You Have To Check Email Is Valid Using This Php Function
$email = test_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
Then If Its Not Valid Give A Error
Else
if (mail ($to, $subject,$txt,$headers)) {
$result='<div class="alert alert-success">Thank You! I will be in touch</div>';
} else {
$result='<div class="alert alert-danger">Sorry there was an error sending your message. Please try again later</div>';
}
try it..
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.
Ok so I am trying to create a contact form that validates user input to keep hackers from submitting codes and trying to require number, text, and email only. I have already styled the form and imported my php file. The contact from will send it to my gmail account. but everytime I test the php It allows for any type of data to be entered no matter if it is supposed to be a number and letters are submitted and the other way around. If I could get some help in telling me where I went wrong that would be great. I am a beginner at programming and only have the knowledge I recieved from school but I'm pretty good at html and css but having problems with the php validation. The form sends the email but like I said it allows any and all input.
<?php
$name = $_POST['name'];
$tel = $_POST['tel'];
$email = $_POST['email'];
$message = $_POST['message'];
$from = 'From: www.webdesignheros.com';
$to = 'heenanwrk#gmail.com';
$subject = 'Service Email for HeenanTech';
$tel = filter_input(INPUT_POST, 'tel', FILTER_SANITIZE_INT);
$name = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_STRING|FILTER_FLAG_NO_ENCODE_QUOTES);
$email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
$message = filter_input(INPUT_POST, 'message', FILTER_SANITIZE_STRING|FILTER_FLAG_NO_ENCODE_QUOTES);
$body = "From: $name\n Phone: $tel\n Email: $email\n Message: $message\n";
?>
<?php
if ($_POST['submit']){
if(mail($to, $subject, $body, $from)){
echo'<p>Thank you for your email!</p>';
} else {
echo '<p> Oops! Something went wrong, try sending your message again</p>';
}
}
?>
Additionally the form can be found at [http://webdesignheros.com/Contact.html][1]
[1]: http://webdesignheros.com/Contact.html and if someone could tell me how to reject certain input before the submit that would be awesome too. like if an invalid entry was input and they move on to the next input it would reject it and not let the submit button be pushed. would i use the pattern="a-z" in the html or would i need to add javascript for that?
<?php
if (isset($_POST["submit")){
$name = $_POST["name"];
$tel = $_POST["tel"];
$email = $_POST["email"];
$message = $_POST["message"];
$from = "From: www.webdesignheros.com";
$to = "heenanwrk#gmail.com";
$subject = "Service Email for HeenanTech";
$body = "From: $name\n Phone: $tel\n Email: $email\n Message: $message\n";
mail($to, $subject, $body, $from);
if(mail($to, $subject, $body, $from)){
echo'<p>Thank you for your email!</p>';
} else {
echo '<p> Oops! Something went wrong, try sending your message again</p>';
}
}
?>
I have the below PHP contact form that has a CAPTCHA code to ensure is correct. However, when I reply to the email from the website it puts a random email which i believe is the server admin, however, I want it to be the persons email who sent the form in. below is the code, could you possibly be able to help me?
<?php session_start();
if(isset($_POST['Submit'])) { if( $_SESSION['chapcha_code'] == $_POST['chapcha_code'] && !empty ($_SESSION['chapcha_code'] ) ) {
$youremail = 'info#example.com';
$fromsubject = 'www.example.co.uk';
$title = $_POST['title'];
$fname = $_POST['fname'];
$mail = $_POST['mail'];
$phone = $_POST['phone'];
$subject = $_POST['subject'];
$message = $_POST['message'];
$to = $youremail;
$mailsubject = 'Message from Website'.$fromsubject.' Contact Page';
$body = $fromsubject.'
The person that contacted you is: '.$fname.'
Phone Number: '.$phone.'
E-mail: '.$mail.'
Subject: '.$subject.'
Message:
'.$message.'
|---------END MESSAGE----------|';
echo "Thank you for your message. I will contact you shortly if needed.<br/>Go to <a href='/index.html'>Home Page</a>";
mail($to, $subject, $body);
unset($_SESSION['chapcha_code']);
} else {
echo 'Sorry, you have provided an invalid security code';
}
} else {
echo "You must write a message. </br> Please go to <a href='/contact.html'>Contact Page</a>";
}
?>
You'll need some headers so the from address is the users mail.
Also refer to the mail docs
try this
$headers = "From: $mail\r\n";
$headers .= "Reply-To: $mail\r\n";
mail($to, $subject,$body,$headers);