Some issue with my php contact form - php

I am trying to make a contact form using PHP and some issue is there. I am new to PHP so couldn't figured it out. The form works if there is no validation code applied but as I apply validation code so that some fields can be made necessary, the form doesn't works right. Moreover when I leave any required field empty then them form doesn't show any error message. Can someone please tell what the problem is.
HTML Form
<form action="mail.php" method="POST" >
Name: <input type="text" name="name"><br/><br/>
Email: <input type="email" name="email"><br/><br/>
Phone Number: <input type="text" name="phone_number"><br/><br/>
Website: <input type="text" name="website"><br/><br/>
Message: <textarea name="message" rows="6" cols="25"></textarea><br/><br/>
<input type="submit" value="Submit">
</form>
Main PHP Script File
<?php
if(isset ($_POST['submit'])) {
$errors = array();
if(!empty ($_POST ['name'])) {
$name = $_POST ['name'];
} else {
$errors[] = "You forgot to enter your Name.";
}
if(!empty ($_POST ['email'])) {
$email = $_POST ['email'];
} else {
$errors[] = "You forgot to enter your Email.";
}
if(!empty ($_POST ['message'])) {
$message = $_POST ['message'];
} else {
$errors[] = "You forgot to enter your Message.";
}
$phone_number = $_POST['phone_number'];
$website = $_POST['website'];
$formcontent = "From: $name \n Email: $email \n Phone Number: $phone_number \n Website: $website \n Message: $message";
$recipient = "yourmail#emial.com";
$subject = "Contact Form";
$mailheader = "From: $email \r\n";
mail($formcontent, $recipient, $subject, $mailheader);
if(isset($_POST['submit'])) {
if(!empty($errors)) {
foreach ($errors as $msg)
{
echo '<li>'. $msg . '</li>';
}
} else {
echo "Thank You";
}
}
}
?>
UPDATE
Thanks for your replies guys, I literally forgot to have name attribute for submit button. That helped for showing some result. But now some notices are showing for undefined variables as email, message (if I provide only name in form and hit submit button) for $formcontent and $mailheader lines.

There are a few things wrong with your code.
if(isset ($_POST['submit'])) you have no name attribute for the submit input to support that, therefore nothing inside that conditional statement will be executed.
Having used error reporting, would have thrown an "Undefined index submit..." warning/notice.
So you need to add one:
<input type="submit" value="Submit" name="submit">
^^^^^^^^^^^^^
Then you have your mail() parameters which are not in the right order.
mail($formcontent, $recipient, $subject, $mailheader);
which should be:
To:
Subject:
Message:
Headers
Change it to:
mail($recipient, $subject, $formcontent, $mailheader);
For more information on mail(), visit the following link on PHP.net:
http://php.net/manual/en/function.mail.php
Edit:
You also need to place mail() function in a different place, where you have your "Thank you". Otherwise, even if an email address is not entered in the form, the mail would still be sent out, thus showing as "unknown sender" in the From. Placing mail() in the else if no errors are found.
if(isset($_POST['submit'])) {
if(!empty($errors)) {
foreach ($errors as $msg)
{
echo '<li>'. $msg . '</li>';
}
} else {
mail($recipient, $subject, $formcontent, $mailheader);
echo "Thank You";
}
}
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Error reporting should only be done in staging, and never production.

You can also add Anti-spam to your form
$q1 = mt_rand(1,10);
$q2 = mt_rand(1,10);
$answer = $q1 + $q2;
<form action="mail.php" method="POST" >
Name: <input type="text" name="name"><br/><br/>
Email: <input type="email" name="email"><br/><br/>
Phone Number: <input type="text" name="phone_number"><br/><br/>
Website: <input type="text" name="website"><br/><br/>
Message: <textarea name="message" rows="6" cols="25"></textarea><br/><br/>
*What is <?php echo $q1 ." + ". $q2;?>? (Anti-spam):
<input type="number" required name="Human" ><br>
<!--question-->
<input name="answer" id="subject" type="hidden" value="<?php echo "$answer"; ?>">
<input type="submit" value="Submit">
</form>
in your form you can check if the answer is correct
<?php
$answer = $_POST['answer'];
if(isset ($_POST['submit']) && $_POST['human'] == answer) {
your mail procesing here
}

Related

Contact Form Disappearing When Div is Set?

Ok, so I've got a contact form:
<?php
if (isset($_POST['subtest'])) {
$to = 'thomofawsome#gmail.com';
$name = $_POST['firstname'];
$lastName = $_POST['lastname'];
$email = $_POST['email'];
$city = $_POST['city'];
$state = $_POST['state'];
$zip = $_POST['zip'];
$comments = $_POST['comments'];
$Message = <<< STOP
From: $name $lastName
Email: $email
In: $city, $state, $zip
Comments: $comments
STOP;
$subject = "Contact Request";
$headers = 'From: system';
if (mail($to, $subject, $Message, $headers)) {
echo '<div id="thanks">Mail sent</div>';
exit();
}
else {
echo 'Mail Failed';
}
}
?>
<form name="contact_form" action="" method="post">
<input type="hidden" name="subtest" value="true">
First Name:<br>
<input type="text" name="firstname">
<br>
Last Name:<br>
<input type="text" name="lastname">
<br>
Email Address:<br>
<input type="text" name="email">
<br>
City:<br>
<input type="text" name="city">
<br>
State:<br>
<input type="text" name="state">
<br>
Zip:<br>
<input type="text" name="zip">
<br>
Comments:<br>
<textarea name="comments"></textarea>
<br>
<input id="submit" type="submit" name="submit" value="Send">
<br>
</form>
The problem is I want the echo mail sent correctly formatted (with a green color, positioned correctly on the page, etc.). As you can see, I've put it in a div. When I submit the form though, I'm redirected back to the form page, except the entire form and footer disappear, and Mail sent appears on the bottom of the page (correctly formatted).
Any ideas?
The exit() function prevents the rest of the script from executing, which includes your form and footer. Remove it and it will work.
if (mail($to, $subject, $Message, $headers)) {
echo '<div id="thanks">Mail sent</div>';
} else {
echo 'Mail Failed';
}
As Raidenance pointed out, if someone refreshes this page after posting the form it will resend the email address. A better solution to this problem is to post your contact form to another url (/contact/submit for instance) and on completion of the script execution at that url simply redirect back to the contact form with a parameter
header("Location:/contact?success=true");
Then on your contact form page:
if (isset($_GET['success']) && $_GET['success'] == "true") {
echo '<div id="thanks">Mail sent</div>';
} else {
echo 'Mail Failed';
}
This will prevent the issue of the user reloading and receiving the email multiple times.

PHP: Wait for User Input Before Executing Script

I have an html input form as well as a php email script that takes these values on the same page.
The problem is that before I submit any data into the forms I get a blank email because my php script is not waiting for the user input.
I don'y wan't to use another page for my email script because I don't want to pass variables through GET and I don't know how to implement sessions yet.
Thanks and here is my code
<div id = "center">
<form action="post.php" name="emailform" method="post">
<input type="text" name="name">
<input type="text" name="email">
<input type="text" name="message">
<input type="submit" value="Send Email">
</form>
</div>
<?php
if (!isset($_POST['submit'])) {
echo 'you have hit the submit button';
$name = $_POST['name'];
$visitor_email = $_POST['email'];
$message = $_POST['message'];
$email_from = 'trustyclient#yoursite.com';
$email_subject = "Message from client";
$email_body = "Message from: $visitor_email \n \n Message:$message";
$to = "myemail#myemail.com";
$headers = "from:adam\r\n";
mail($to,$email_subject,$email_body,$headers);
} else {
echo 'You have not hit the submit button yet';
}
?>
First, give your submit button a name, like 'submit' (because you've already referenced that name in the PHP). Example:
<input type="submit" name="submit" value="Send Email">
Now you can actually use $_POST['submit'] in your code.
Then another tweak:
When you state if (!isset($_POST['submit'])) {, the following code runs if the submit button has not been pressed, because of the !. To fix, just remove the !, making it:
if (isset($_POST['submit'])) {
! tells the if statement to evaluate to true if the following expression, here isset($_POST['submit']), evaluates to false. Therefore ! means "if the opposite".
NB: Also, the concept that the PHP runs when the submit button is pressed is slightly off. The submit button triggers that page to load a different page (or the same page). The PHP code runs only once when the page loads.
Try this.
<div id = "center">
<form action="post.php" name="emailform" method="post">
<input type="text" name="name">
<input type="text" name="email">
<input type="text" name="message">
<input type="submit" value="Send Email">
</form>
</div>
<?php
if (isset($_POST['submit'])) {
echo 'you have hit the submit button';
if (empty(trim($_POST['name'])) || empty(trim($_POST['email'])) || empty(trim($_POST['message']))) {
echo 'Some fields are empty.';
} else {
$name = $_POST['name'];
$visitor_email = $_POST['email'];
$message = $_POST['message'];
$email_from = 'trustyclient#yoursite.com';
$email_subject = "Message from client";
$email_body = "Message from: $visitor_email \n \n Message:$message";
$to = "myemail#myemail.com";
$headers = "from:adam\r\n";
mail($to,$email_subject,$email_body,$headers);
}
} else {
echo 'You have not hit the submit button yet';
}
?>

send html form with php can't solve

I have big problem with sending easy html form with php.
My problem is when all fields are empty it still send message.
I don't why this code still send empty form??
<form id="form1" name="form1" method="post" action="forma.php">
<p>
<label for="ime">Ime:</label>
<input type="text" name="ime" id="ime" />
</p>
<p>
<label for="prezime">Prezime:</label>
<input type="text" name="prezime" id="prezime" />
</p>
<p>
<label for="email">e-mail:</label>
<input type="text" name="email" id="email" />
</p>
<p>
<label for="poruka">Poruka:</label>
<textarea name="poruka" cols="40" rows="10" id="poruka"></textarea>
</p>
<p>
<input type="submit" name="submit" value="submit" />
</p>
</form>
My php code:
<?php
if (isset($_POST['submit']))
{
$ime= $_POST['ime'];
$prezime= $_POST['prezime'];
$email= $_POST['email'];
$poruka= $_POST['poruka'];
$email_from = 'neki#email.com';
$email_subject = "forma sa sajta";
$email_body = "Ime: $ime. \n". "Prezime: $prezime \n". "email: $email \n". "poruka: $poruka" ;
$to = "myemail#gmail.com";
mail ($to, $email_subject, $email_body);
echo "Message is sent";
}
else {
echo "Message is not sent";
}
?>
So again, when i fill fields message is sent. It is ok, i received email.
But when i just click submit (without filling fields) it still send message to my email.
What is wrong with this code? I try everything i know, but without success.
Thank you.
The problem is that you are only checking to see if "submit" is set.
Your if statement should read something like:
if(isset($_POST['submit']) && all_other_fields_are_valid($_POST)){...}
function all_other_fields_are_valid($fields)
{
//logic to decide what fields and values you require goes here
}
You need to check all required field. only check submit it will attempt mailing:
if (isset($_POST['submit']
, $_POST['ime']
, $_POST['prezime']
, $_POST['email']
, $_POST['poruka']))
Additionally you can validate from the client side using new HTML5 required attribute:
<input type="text" name="ime" id="ime" required />
This way you don't waste server resources for bad formed requests.
Actually since they are sent as empty variables, they will still evaluate to true in isset(), even if there is no text in the input fields when they are submitted.
if($_POST['ime'] && $_POST['prezime'] && $_POST['email'] && $_POST['poruka']) {
// do stuff here
}
As long as all of these have values and none of the values are 'false' or '0', this will evaluate to true only if somebody puts text in all of the input fields.
This will check if all required POST vars are set, if they're empty and give an error if so:
<?php
if (isset($_POST['submit'], $_POST['ime'], $_POST['prezime'], $_POST['email'], $_POST['poruka']))
{
$error = "";
if($_POST['ime'] == ""){
$error .= "ima was empty!<br />";
}
if($_POST['prezime'] == ""){
$error .= "prezime was empty!<br />";
}
if($_POST['email'] == ""){
$error .= "email was empty!<br />";
}
if($_POST['poruka'] == ""){
$error .= "poruka was empty!<br />";
}
if($error == ""){
$ime= $_POST['ime'];
$prezime= $_POST['prezime'];
$email= $_POST['email'];
$poruka= $_POST['poruka'];
$email_from = 'neki#email.com';
$email_subject = "forma sa sajta";
$email_body = "Ime: $ime. \n". "Prezime: $prezime \n". "email: $email \n". "poruka: $poruka" ;
$to = "myemail#gmail.com";
mail ($to, $email_subject, $email_body);
echo "Message is sent";
} else {
echo $error;
}
} else {
echo "Message is not sent";
}
?>

Form isn't sending

I'm staging a site for a client and I'm trying to create a form from scratch rather than use a plugin.
I'm not sure where I'm going wrong. The page keeps refreshing to the homepage and no email gets sent.
Could someone please point out in my code where I've gone wrong...
Thanks in advance!
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$from = 'From: Test';
$to = 'email#example.com';
$subject = 'Hello';
if ($name == "" OR $email == "") {
echo "You must specify a value for name, email address, and message.";
exit;
}
foreach( $_POST as $value ){
if( stripos($value,'Content-Type:') !== FALSE ){
echo "There was a problem with the information you entered.";
exit;
}
}
require_once("assets/inc/phpmailer/class.phpmailer.php");
$mail = new PHPMailer();
if (!$mail->ValidateAddress($email)){
echo "You must specify a valid email address.";
}
$body = "From: $name\n E-Mail: $email\n Message:\n $message";
header("Location: http://natashamcdiarmid.com/clients/JLP/wp/contact/?status=thanks");
exit;
}
?>
<?php if (isset($_GET["status"]) AND $_GET["status"] == "thanks") { ?>
<p>Thanks, I'll get back to your shortly!</p>
<?php } else ?>
<form method="post" action="contact">
<p><label>Name</label></p>
<input name="name" placeholder="Type Here">
<p><label>Email</label></p>
<input name="email" type="email" placeholder="Type Here">
<p><label>Message</label></p>
<textarea name="message" placeholder="Type Here"></textarea>
<p><label>*What is 2+2?</label></p>
<input name="human" placeholder="Type Here">
<p><input id="submit" name="submit" type="submit" value="Submit"></p>
<?php
if ($_POST['submit']) {
if (mail ($to, $subject, $body, $from)) {
echo '<p>Your message has been sent!</p>';
} else {
echo '<p>Something went wrong, go back and try again!</p>';
}
}
?>
</form>
The form that you are posting to isn't much of a directory.
<form method="post" action="contact">
should it be contact.php?
this action should be the directory of your form handler
A major issue with WordPress that always gets me is that it uses some request variables with common names, and messing with them causes unpredictable errors. For instance, the name parameter is used to locate and display the current post or web page.
Try renaming your name field to something else, like your_name.
When I create forms for use in WordPress, typically I prefix every field with something custom, like acme_contact_name, acme_contact_email, etc. A little more typing, but safer.

My PHP Contact Form is not working

I am creating a website and I was making a contact form with PHP. It is turning up no errors on the page itself but the email never shows up in the inbox or spam folder of my email. The code I have for it is:
$_NAME = $_POST["name"];
$_EMAIL = $_POST["reply"];
$_SUBJECT = $_POST["subject"];
$_MESSAGE = $_POST["message"];
$_MAILTO = "myemail#gmail.com";
$_SUBJECT = "Contact Form";
$_FORMCONTENT = "From: ".$_NAME." Subject: ".$_SUBJECT." Message: ".$_MESSAGE;
$_MAILHEADER = "Reply To: ".$_EMAIL;
mail($_MAILTO, $_SUBJECT, $_FORMCONTENT, $_MAILHEADER);
Any ideas what the problem is?
EDIT --
Here's the HTML form:
<form id="contact" name="contact" action="contact2.php" method="post">
<input type="text" class="name" name="name" id="name" placeholder="Your name (optional)" onfocus="placeholder=''" onblur="placeholder='Your name (optional)'" /><br><br>
<input type="text" class="reply" id="reply" name="reply" placeholder="Your email (optional)" onfocus="placeholder=''" onblur="placeholder='Your email (optional)'" /><br><br>
<input type="text" class="subject" id="subject" name="subject" placeholder="Subject" onfocus="placeholder=''" onblur="placeholder='Subject'" /><br><br>
<textarea class="message" id="message" name="message" rows="10" cols="50" placeholder="Enter your message" onfocus="placeholder=''" onblur="placeholder='Enter your message'"></textarea><br><br>
<input type="submit" class="send" id="send" name="send" value="Send Message" />
</form>
First step would be to check the return value of the mail function to see if the email was successfully (as far as PHP/mail function can ascertain) sent.
$mail_result = mail($_MAILTO, $_SUBJECT, $_FORMCONTENT, $_MAILHEADER);
if ($mail_result) {
echo <<<HTML
<div>Mail was successfully sent!</div>
HTML;
} else {
echo <<<HTML
<div>Sending mail failed!</div>
HTML;
}
Secondly, you should check that all appropriate settings are correctly set in your php.ini file, specifically the sendmail_path setting. You should definitely take a look at official documentation in the PHP Manual.
As a last ditch effort, you may want to look into an alternate method of sending the mail.
Simple Example:
<?php
// Has the form been submitted?
if (isset($_POST['send'])) {
// Set some variables
$required_fields = array('name', 'email'); // add fields as needed
$errors = array();
$success_message = "Congrats! Your message has been sent successfully!";
$sendmail_error_message = "Oops! Something has gone wrong, please try later.";
// Cool the form has been submitted! Let's loop
// through the required fields and check
// if they meet our condition(s)
foreach ($required_fields as $fieldName) {
// If the current field in the loop is NOT part of the form submission -OR-
// if the current field in the loop is empty
if (!isset($_POST[$fieldName]) || empty($_POST[$fieldName])) {
// add a reference to the errors array, indicating that these conditions have failed
$errors[$fieldName] = "The {$fieldName} is required!";
}
}
// Proceed if there aren't any errors
if (empty($errors)) {
// add fields as needed
$name = htmlspecialchars(trim($_POST['name']), ENT_QUOTES, 'UTF-8' );
$email = htmlspecialchars(trim($_POST['email']), ENT_QUOTES, 'UTF-8' );
// Email receivers
$to_emails = "anonymous1#example.com, anonymous2#example.com";
$subject = 'Contact form sent from ' . $name;
$message = "From: {$name}";
$message .= "Email: {$email}";
$headers = "From: {$name}\r\n";
$headers .= "Reply-To: {$email}\r\n";
$headers .= 'X-Mailer: PHP/' . phpversion();
if (mail($to_emails, $subject, $message, $headers)) {
echo $success_message;
} else {
echo $sendmail_error_message;
}
} else {
foreach($errors as $invalid_field_msg) {
echo "<p>{$invalid_field_msg}</p>";
}
}
}

Categories