I am attempting to create a working PHP contact form - php

At the bottom of this page under the section 'Quick Message' in the lower right there is a a contact form I'm trying to fix.
http://danielgruttadaro.chapter7ny.com
The form does not allow submissions that do not have all three sections filled out. However, I am receiving the error: 'sorry unexpected error please try again later' when the form is properly filled out. Below is the relevant html and php. Thanks for your help.
<form method="post" action="contact.php" id="contactform">
<div class="form">
<input class="col-md-6" type="text" name="name" placeholder="Name">
<input class="col-md-6" type="text" name="email" placeholder="E-mail">
<textarea class="col-md-12" name="message" rows="4" placeholder="Message"></textarea>
<input type="submit" id="submit" class="btn" value="Send">
</div>
Here is the php:
<?php
//Retrieve form data.
//GET - user submitted data using AJAX
//POST - in case user does not support javascript, we'll use POST instead
$name = ($_GET['name']) ? $_GET['name'] : $_POST['name'];
$email = ($_GET['email']) ?$_GET['email'] : $_POST['email'];
$message = ($_GET['message']) ?$_GET['message'] : $_POST['message'];
//flag to indicate which method it uses. If POST set it to 1
if ($_POST) $post=1;
//Simple server side validation for POST data, of course, you should validate the email
if (!$name) $errors[count($errors)] = 'Please enter your name.';
if (!$email) $errors[count($errors)] = 'Please enter your email.';
if (!$message) $errors[count($errors)] = 'Please enter your message.';
//if the errors array is empty, send the mail
if (!$errors) {
//recipient - replace your email here
$to = 'dan#chapter7ny.com';
//sender - from the form
$from = $name . ' <' . $email . '>';
//subject and the html message
$subject = 'Message from ' . $name;
$message = 'Name: ' . $name . '<br/><br/>
Email: ' . $email . '<br/><br/>
Message: ' . nl2br($message) . '<br/>';
//send the mail
$result = sendmail($to, $subject, $message, $from);
//if POST was used, display the message straight away
if ($_POST) {
if ($result) echo 'Thank you! We have received your message.';
else echo 'Sorry, unexpected error. Please try again later';
//else if GET was used, return the boolean value so that
//ajax script can react accordingly
//1 means success, 0 means failed
} else {
echo $result;
}
//if the errors array has values
} else {
//display the errors message
for ($i=0; $i<count($errors); $i++) echo $errors[$i] . '<br/>';
echo 'Back';
exit;
}
//Simple mail function with HTML header
function sendmail($to, $subject, $message, $from) {
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
$headers .= 'From: ' . $from . "\r\n";
$result = mail($to,$subject,$message,$headers);
if ($result) return 1;
else return 0;
}
?>

Most likely the machine that is running php doesn't have a mail server set up as well. The mail function requires that. You can use a library like:
https://github.com/PHPMailer/PHPMailer
and use an existing gmail account to send your email:
http://phpmailer.worxware.com/?pg=examplebgmail
which will let you mail yourself whatever they type in. This is what I use in almost all of my projects.
You can also use PEAR:
https://pear.php.net/package/Mail
Which I have also had luck with in the past. Godspeed.

Related

How to integrate reCAPTCHA with a form

I can't work out how to add Google reCAPTCHA to this contact form. I have no problems adding on the front end but can't seem to apply to the server side.
<!-- Form -->
<div id="contact-form">
<form method="post" action="contact.php">
<div class="field">
<label>Name:</label>
<input type="text" name="name" class="text" />
</div>
<div class="field">
<label>Email: <span>*</span></label>
<input type="text" name="email" class="text" />
</div>
<div class="field">
<label>Message: <span>*</span></label>
<textarea name="message" class="text textarea" ></textarea>
</div>
<div class="field">
<input type="button" class="button light medium" id="send" value="Send Message"/>
</div>
<div class="field">
<input type="button" class="button gray medium" value="Reset!"/>
</div>
<div class="loading"></div>
</form>
</div>
PHP Server Side
<?php
//Retrieve form data.
//GET - user submitted data using AJAX
//POST - in case user does not support javascript, we'll use POST instead
$name = ($_GET['name']) ? $_GET['name'] : $_POST['name'];
$email = ($_GET['email']) ?$_GET['email'] : $_POST['email'];
$message = ($_GET['message']) ?$_GET['message'] : $_POST['message'];
//flag to indicate which method it uses. If POST set it to 1
if ($_POST) $post=1;
//Simple server side validation for POST data, of course, you should validate the email
if (!$name) $errors[count($errors)] = 'Please enter your name.';
if (!$email) $errors[count($errors)] = 'Please enter your email.';
if (!$message) $errors[count($errors)] = 'Please enter your message.';
//If the errors array is empty, send the mail
if (!$errors) {
// ====== Your mail here ====== //
$to = 'admin#mysite.com <admin#mysite.com>';
// Sender
$from = $name . ' <' . $email . '>';
//subject and the html message
$subject = 'Contact Message from the Byblos Group Website';
$message = '
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head></head>
<body>
<table>
<tr><td>Name:</td><td>' . $name . '</td></tr>
<tr><td>Email:</td><td>' . $email . '</td></tr>
<tr><td>Message:</td><td>' . nl2br($message) . '</td></tr>
</table>
</body>
</html>';
// Send the mail
$result = sendmail($to, $subject, $message, $from);
//if POST was used, display the message straight away
if ($_POST) {
if ($result) echo 'Thank you! We have received your message.';
else echo 'Sorry, unexpected error. Please try again later';
//else if GET was used, return the boolean value so that
//ajax script can react accordingly
//1 means success, 0 means failed
} else {
echo $result;
}
// If the errors array has values
} else {}
// Simple mail function with HTML header
function sendmail($to, $subject, $message, $from) {
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
$headers .= 'From: ' . $from . "\r\n";
$result = mail($to,$subject,$message,$headers);
if ($result) return 1;
else return 0;
}
?>
We are validating google reCAPTCHA like this
$fileContent = '';
if (isset($_REQUEST['g-recaptcha-response']) && !empty($_REQUEST['g-recaptcha-response'])) {
$fileContent = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=your_recaptcha_secret_key&response=". $_REQUEST['g-recaptcha-response']);
}
$jsonArray = json_decode($fileContent, true);
if (isset($jsonArray['success']) && $jsonArray['success']==true) {
// process your logic here
} else {
echo 'Invalid verification code, please try again!';
}
I'm actually using this self-made function to check if reCAPTCHA is valid on my website
function checkCaptcha($cResp) {
$captchaSecret = "yourSecret";
$captchaRequestUrl = 'https://www.google.com/recaptcha/api/siteverify?secret='.$captchaSecret.'&response='.$cResp;
$captchaResponse = #file_get_contents($captchaRequestUrl);
if (!$captchaResponse) {
return 2;
}
$captchaResponse = json_decode($captchaResponse);
$captchaSuccess = $captchaResponse->{'success'};
if (!$captchaSuccess) {
return 3;
}
return 1;
}
Then you can check like the following
if (checkCaptcha($_POST['g-recaptcha-response']) === 1) // success
if (checkCaptcha($_POST['g-recaptcha-response']) === 2) // no resp
if (checkCaptcha($_POST['g-recaptcha-response']) === 3) // fail

PHP email contact form displays error

Every time I attempt to submit this contact form I receive the following error message:
'Please enter your message.'
The name error message and email error message do not appear unless I leave them blank. I attempted specifying post in the HTML.
Here is the HTML:
<div class="col-md-8 animated fadeInLeft notransition">
<h1 class="smalltitle">
<span>Get in Touch</span>
</h1>
<form action="contact.php" method="post" name="MYFORM" id="MYFORM">
<input name="name" size="30" type="text" id="name" class="col-md-6 leftradius" placeholder="Your Name">
<input name="email" size="30" type="text" id="email" class="col-md-6 rightradius" placeholder="E-mail Address">
<textarea id="message" name="message" class="col-md-12 allradius" placeholder="Message" rows="9"></textarea>
<img src="contact/refresh.jpg" width="25" alt="" id="refresh"/><img src="contact/get_captcha.php" alt="" id="captcha"/>
<br/><input name="code" type="text" id="code" placeholder="Enter Captcha" class="top10">
<br/>
<input value="Send" type="submit" id="Send" class="btn btn-default btn-md">
</form>
</div>
Here is the PHP:
<?php
//Retrieve form data.
//GET - user submitted data using AJAX
//POST - in case user does not support javascript, we'll use POST instead
$name = ($_GET['name']) ? $_GET['name'] : $_POST['name'];
$email = ($_GET['email']) ?$_GET['email'] : $_POST['email'];
$comment = ($_GET['comment']) ?$_GET['comment'] : $_POST['comment'];
//flag to indicate which method it uses. If POST set it to 1
if ($_POST) $post=1;
//Simple server side validation for POST data, of course, you should validate the email
if (!$name) $errors[count($errors)] = 'Please enter your name.';
if (!$email) $errors[count($errors)] = 'Please enter your email.';
if (!$comment) $errors[count($errors)] = 'Please enter your message.';
//if the errors array is empty, send the mail
if (!$errors) {
//recipient - replace your email here
$to = 'faasdfsdfs#gmail.com';
//sender - from the form
$from = $name . ' <' . $email . '>';
//subject and the html message
$subject = 'Message from ' . $name;
$message = 'Name: ' . $name . '<br/><br/>
Email: ' . $email . '<br/><br/>
Message: ' . nl2br($comment) . '<br/>';
//send the mail
$result = sendmail($to, $subject, $message, $from);
//if POST was used, display the message straight away
if ($_POST) {
if ($result) echo 'Thank you! We have received your message.';
else echo 'Sorry, unexpected error. Please try again later';
//else if GET was used, return the boolean value so that
//ajax script can react accordingly
//1 means success, 0 means failed
} else {
echo $result;
}
//if the errors array has values
} else {
//display the errors message
for ($i=0; $i<count($errors); $i++) echo $errors[$i] . '<br/>';
echo 'Back';
exit;
}
//Simple mail function with HTML header
function sendmail($to, $subject, $message, $from) {
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
$headers .= 'From: ' . $from . "\r\n";
$result = mail($to,$subject,$message,$headers);
if ($result) return 1;
else return 0;
}
In your HTML form you name your <input... field "message" but then when you are in PHP you try to get the value from `$_GET['comment'].
I think if you get those lined up I think it will solve your problem.
I can see 2 issues:
Receive $_GET['comment'] or $_POST['comment'] but next you're using $message var
Do not use if($_POST) because $_POST as a superglobal
is always setted.
I suggest use this for check if a POST have been sent
if ( $_SERVER['REQUEST_METHOD'] == 'POST' ) {}
or this in case you want to check is not empty
if ( !empty($_POST) ) {}
How to detect if $_POST is set?

Why my form submission does not work with php? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I'm trying to get this form submission working, but I'm not familiar with php. I have bought this but it does not seem to be working.
When I press the submit button nothing will happen! I'm just trying to find out if the code is written correctly.
Thank you in advance
HTML Code
<form method="post" id="contact-form" action="contact.php">
<div class="fields">
<div class="column">
<div class="field">
<input type="text" name="name" placeholder="Name*">
</div>
</div>
<div class="columnlast">
<div class="field">
<input type="text" name="email" placeholder="Email*">
</div>
</div>
</div>
<textarea cols="1" name="message" rows="4" placeholder="Message"></textarea>
<input type="submit" value="Submit">
</form>
PHP Code
<?php
//Retrieve form data.
//GET - user submitted data using AJAX
//POST - in case user does not support javascript, we'll use POST instead
$name = isset($_GET['name']) ? $_GET['name'] : $_POST['name'];
$email = isset($_GET['email']) ?$_GET['email'] : $_POST['email'];
$phone = isset($_GET['phone']) ?$_GET['phone'] : $_POST['phone'];
$message = isset($_GET['message']) ?$_GET['message'] : $_POST['message'];
if ($_POST) $post=1;
$errors = array();
if (!$name) $errors[count($errors)] = 'Please enter your name.';
if (!$phone) $errors[count($errors)] = 'Please enter your phone.';
if (!$email) $errors[count($errors)] = 'Please enter your email.';
if (!$message) $errors[count($errors)] = 'Please enter your message.';
//If the errors array is empty, send the mail
if (!$errors) {
// ====== mail here ====== //
$to = 'Ardi Mir <ardmir87#hotmail.com>';
// Sender
$from = $name . ' <' . $email . '>';
//subject and the html message
$subject = 'Message from your website';
$message = '
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head></head>
<body>
<table>
<tr><td>Name:</td><td>' . $name . '</td></tr>
<tr><td>Phone:</td><td>' . $phone . '</td></tr>
<tr><td>Email:</td><td>' . $email . '</td></tr>
<tr><td>Message:</td><td>' . nl2br($message) . '</td></tr>
</table>
</body>
</html>';
$result = sendmail($to, $subject, $message, $from);
if ($_POST) {
if ($result) echo 'Thank you! We have received your message.';
else echo 'Sorry, unexpected error. Please try again later';
} else {
echo $result;
}
} else {}
function sendmail($to, $subject, $message, $from) {
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
$headers .= 'From: ' . $from . "\r\n";
$result = mail($to,$subject,$message,$headers);
if ($result) return 1;
else return 0;
}
?>
The reason why your form is not working and mail not sending is because it is missing the phone field.
Add the following to your HTML form:
<input type="text" name="phone" placeholder="Phone*">
and it will work.
If error reporting were set/included in your PHP, it would have thrown the following, or similar to:
Notice: Undefined index: phone in /path/to/your/file.php on line X
Add error reporting to the top of your file(s) which will help during production testing.
error_reporting(E_ALL);
ini_set('display_errors', 1);
This was tested on my own hosted service and not a local machine.
I have quickly put your code on my local webserver and looked into it.
First on, replace
if(!$errors)
with
if(empty($errors))
if you use !$variable, then PHP will check if the variable is a bool with content FALSE.
$foo=false;
if(!$foo) {...} else {...}
Next on, you are expecting a phone number.
Array ( [0] => Please enter your phone. )
I figured this out by putting the following at line 56 of your code:
} else {print_r($errors);}
print_r(...) lets you view the contents of a variable in a human readable format. Its often used for debugging.
Otherwise, I have not spotted any error. So what you have to fix, in a nutshell:
Replace the if-statement above to correctly check for an empty array.
Never leave an else statement blank while debugging, that could become a pitfall. Use print_r during debugging, but nto during production, as it could offer somebody some valuable information about your code/setup.
The PHP manual also has some nice things about the empty() function to tell: http://php.net/empty
Same for print_r: http://php.net/print_r

Sending mail in PHP results in undefined index

I am trying to get my contact form on my site to operate correctly. I am getting undefined index in regards to the $name, $email, $thesubject, $message variables, respectively.
Could anyone tell me what I need to do to get the email to properly send?
HTML/Form:
<div class="alert success success-message">
<div class="close">×</div>
<p>Your message has been sent!</p>
</div>
<form class="clearfix" method="post" action="contact.php">
<div class="field">
<label>Name <span>*</span></label>
<input type="text" name="name" class="text" value="" />
</div>
<div class="field">
<label>Email <span>*</span></label>
<input type="email" name="email" class="text" value="" />
</div>
<div class="field field-last">
<label>Subject <span>*</span></label>
<input type="text" name="thesubject" class="text" value="" />
</div>
<textarea name="message" class="text"></textarea>
<button id="send" class="btn">Submit</button>
<div class="loading"></div>
</form>
</div>
PHP:
<?php
//Retrieve form data.
//GET - user submitted data using AJAX
//POST - in case user does not support javascript, we'll use POST instead
$name = ($_GET['name']) ? $_GET['name'] : $_POST['name'];
$email = ($_GET['email']) ?$_GET['email'] : $_POST['email'];
$thesubject = ($_GET['thesubject']) ?$_GET['thesubject'] : $_POST['thesubject'];
$message = ($_GET['message']) ?$_GET['message'] : $_POST['message'];
//flag to indicate which method it uses. If POST set it to 1
if ($_POST) $post=1;
//Simple server side validation for POST data, of course, you should validate the email
if (!$name) $errors[count($errors)] = 'Please enter your name.';
if (!$email) $errors[count($errors)] = 'Please enter your email.';
if (!$thesubject) $errors[count($errors)] = 'Please enter your subject.';
if (!$message) $errors[count($errors)] = 'Please enter your message.';
//if the errors array is empty, send the mail
if (!$errors) {
// ====== Your mail here ====== //
$to = 'myemail#gmail.com';
//sender
$from = $name . ' <' . $email . '>';
//subject and the html message
$subject = 'yourwebsite.com / ' . $thesubject . '';
$message = '
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head></head>
<body>
<table>
<tr><td>Name:</td><td>' . $name . '</td></tr>
<tr><td>Email:</td><td>' . $email . '</td></tr>
<tr><td>Message:</td><td>' . nl2br($message) . '</td></tr>
</table>
</body>
</html>';
//send the mail
$result = sendmail($to, $subject, $message, $from);
//if POST was used, display the message straight away
if ($_POST) {
if ($result) echo 'Thank you! We have received your message.';
else echo 'Sorry, unexpected error. Please try again later';
//else if GET was used, return the boolean value so that
//ajax script can react accordingly
//1 means success, 0 means failed
} else {
echo $result;
}
//if the errors array has values
} else {}
//Simple mail function with HTML header
function sendmail($to, $subject, $message, $from) {
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
$headers .= 'From: ' . $from . "\r\n";
$result = mail($to,$subject,$message,$headers);
if ($result) return 1;
else return 0;
}
?>
use isset function to check if variable is setup. For example:
$name = isset($_GET['name']) ? $_GET['name'] : $_GET['name'];

PHP Mail form not sending emails on Linux server

This is my code and my form... it acts like the email was sent, but it never arrives.
I would like to know what could possibly be wrong... Anyone?
The website is hosted on a Linux server, and I don't really know if the server could be blocking the emails because of some kind of incompatibility... I don't really know what it could be.
<?php
if($_POST)
{
//check if its an ajax request, exit if not
if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
die();
}
$to_Email = "myemail#gmail.com"; //Replace with recipient email address
$subject = 'Ah!! My email from Somebody out there...'; //Subject line for emails
//check $_POST vars are set, exit if any missing
if(!isset($_POST["userName"]) || !isset($_POST["userEmail"]) || !isset($_POST["userPhone"]) || !isset($_POST["userMessage"]))
{
die();
}
//Sanitize input data using PHP filter_var().
$user_Name = filter_var($_POST["userName"], FILTER_SANITIZE_STRING);
$user_Email = filter_var($_POST["userEmail"], FILTER_SANITIZE_EMAIL);
$user_Phone = filter_var($_POST["userPhone"], FILTER_SANITIZE_STRING);
$user_Message = filter_var($_POST["userMessage"], FILTER_SANITIZE_STRING);
//additional php validation
if(strlen($user_Name)<4) // If length is less than 4 it will throw an HTTP error.
{
header('HTTP/1.1 500 Name is too short or empty!');
exit();
}
if(!filter_var($user_Email, FILTER_VALIDATE_EMAIL)) //email validation
{
header('HTTP/1.1 500 Please enter a valid email!');
exit();
}
if(!is_numeric($user_Phone)) //check entered data is numbers
{
header('HTTP/1.1 500 Only numbers allowed in phone field');
exit();
}
if(strlen($user_Message)<5) //check emtpy message
{
header('HTTP/1.1 500 Too short message! Please enter something.');
exit();
}
//proceed with PHP email.
$headers = 'From: '.$user_Email.'' . "rn" .
'Reply-To: '.$user_Email.'' . "rn" .
'X-Mailer: PHP/' . phpversion();
#$sentMail = mail($to_Email, $subject, $user_Message .' -'.$user_Name, $headers);
if(!$sentMail)
{
header('HTTP/1.1 500 Couldnot send mail! Sorry..');
exit();
}else{
echo 'Hi '.$user_Name .', Thank you for your email! ';
echo 'Your email has already arrived in my Inbox, all I need to do is Check it.';
}
}
?>
Here's my form:
<fieldset id="contact_form">
<legend>My Contact Form</legend>
<div id="result"></div>
<input type="text" name="name" id="inputt" placeholder="Enter Your Name" />
<input type="text" name="email" id="inputt" placeholder="Enter Your Email" />
<input type="text" name="phone" id="inputt" placeholder="Phone Number" />
<textarea name="message" id="message" placeholder="Enter Your Name"></textarea>
<button class="submit_btn" id="submit_btn">Submit</button>
</fieldset>
Your $headers are wrong, you're appending "rn" instead of "\r\n". Try this instead:
$headers = 'From: '.$user_Email. "\r\n" .
'Reply-To: '.$user_Email. "\r\n" .
'X-Mailer: PHP/' . phpversion();
According from your comment out of the maillog you need to adjust your php.ini to include the --r argument to your sendmail_path.
By default it usually is:
sendmail_path = /usr/sbin/sendmail -t -i
Apparently you are using another argument that also requires the --r argument. Appending that to your sendmail_path should get a long way.

Categories