I am not a PHP programmer, but have used it a touch, enough to put in a contact form. However, I am trying to add a captcha field, which now works but the form does not validate it - so it submits no matter what
Can anybody help please? sorry if the code is messy and thanks in advance
code at the top of my page
<?php session_start() ?>
<?php
//If the form is submitted
if(isset($_POST['submit'])) {
//Check to make sure that the name field is not empty
if(trim($_POST['name']) == '') {
$hasError = true;
} else {
$name = trim($_POST['name']);
}
//Check to make sure that the subject field is not empty
if(trim($_POST['subject']) == '') {
$hasError = true;
} else {
$subject = trim($_POST['subject']);
}
//Check to make sure sure that a valid email address is submitted
if(trim($_POST['email']) == '') {
$hasError = true;
} else if (!eregi("^[A-Z0-9._%-]+#[A-Z0-9._%-]+\.[A-Z]{2,4}$", trim($_POST['email'])))
{
$hasError = true;
} else {
$email = trim($_POST['email']);
}
//Check to make sure comments were entered
if(trim($_POST['message']) == '') {
$hasError = true;
} else {
if(function_exists('stripslashes')) {
$message = stripslashes(trim($_POST['message']));
} else {
$message = trim($_POST['message']);
}
/*captcha 2*/
if(isset($_POST["captcha"])) {
$hasError = true;
} else {
if($_SESSION["captcha"]==$_POST["captcha"]) {
}
}
//CAPTHCA is valid; proceed the message: save to database, send by e-mail ...
//If there is no error, send the email
if(!isset($hasError)) {
$emailTo = 'email address'; //Put your own email address here
$emailTo = 'email address'; //Put your own email address here
$body = "Name: $name \n\nEmail: $email \n\nSubject: $subject \n\nMessage:\n $message";
$headers = 'From: website form <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' .
$email;
mail($emailTo, $subject, $body, $headers);
$emailSent = true;
}
}
?>
Code in the form:
[php]<?php if(isset($hasError)) { //If errors are found ?>
<p class="error">Please check if you've filled all the fields with valid information. Thank you.</p>
<?php } ?>
<?php if(isset($emailSent) && $emailSent == true) { //If email is sent ?>
<p><strong>Email Successfully Sent!</strong></p>
<p>Thank you <strong><?php echo $name;?></strong> for contacting us. Your email was successfully sent and we will be in touch with you soon.</p>
<?php } ?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" id="contactform">
<div>
<p>
<label for="name">Name</label><br />
<input type="text" name="name" value="" id="name" class="required">
</p>
</div>
<div>
<p>
<label for="email">Email</label><br />
<input type="text" name="email" value="" id="email" class="required">
</p>
</div>
<div>
<p>
<label for="subject">Subject</label><br />
<input type="text" name="subject" value="" id="subject" class="required">
</p>
</div>
<div style="margin-bottom:25px;">
<p>
<label for="message">Message</label><br />
<textarea rows="5" name="message" value="" id="message" class="required"></textarea>
</p>
</div>
<div style="margin-bottom:25px;">
<img src="captcha.php" alt="captcha image">
<p>
<label for="captcha">(antispam code, 3 black symbols)</label><br />
<input type="text" name="captcha" maxlength="3" id="captcha" class="required">
</p>
</div>
<input type="submit" value="Send Message" name="submit" />
</form>
[/php]
[edit ] 2011-12-20 8:22pm CST - updated the second block of code with the final code that the OP is using - based on off site chat.
There's a better way to write the code. I'm putting an example of this below. Ask questions and I'll update the code with comments explaining. I revamped the if statement you had for the captcha so that it didn't need a double if. Using || (or) in the if statement causes PHP to stop after testing the first condition (if the first condition evaluates to true). Therefore, if the variable is not set it never moves on to the comparison of POST with SESSION.
Also, I defaulted your hasError variable to false, and am testing for the boolean value. This is better because it makes sense. Think about the programmers who will come after you. If it makes sense, it'll be easier to work with. You might be that programmer :)
[edited to add session_start();]
<?php
session_start();
// default value
$hasError = false;
//If the form is submitted
if(isset($_POST['submit'])) {
//Check to make sure that the name field is not empty
if(trim($_POST['name']) == '') {
$hasError = true;
} else {
$name = trim($_POST['name']);
}
//Check to make sure that the subject field is not empty
if(trim($_POST['subject']) == '') {
$hasError = true;
} else {
$subject = trim($_POST['subject']);
}
//Check to make sure sure that a valid email address is submitted
if(trim($_POST['email']) == '') {
$hasError = true;
} else if (!eregi("^[A-Z0-9._%-]+#[A-Z0-9._%-]+\.[A-Z]{2,4}$", trim($_POST['email']))) {
$hasError = true;
} else {
$email = trim($_POST['email']);
}
//Check to make sure comments were entered
if( trim($_POST['message']) == '') {
$hasError = true;
} else {
if(function_exists('stripslashes')) {
$message = stripslashes(trim($_POST['message']));
} else {
$message = trim($_POST['message']);
}
}
if( ! isset( $_POST["captcha"] ) || $_SESSION["captcha"] != $_POST["captcha"] ) {
$hasError = true;
echo 'CAPTHCA is not valid; ignore submission<br>';
echo $_POST['captcha' . ' != ' . $_SESSION['captcha'] . '<br>';
}
//If there is no error, send the email
if( $hasError == false ) {
$emailTo = 'email#email.com'; //Put your own email address here
$emailTo = 'email#email.com'; //Put your own email address here
$body = "Name: $name \n\nEmail: $email \n\nSubject: $subject \n\nMessage:\n $message";
// !!!!!!!!!!!!!!!! REMOVE \r\n from $emailTo or your form will be hacked !!!!!!!!!!!!!!!!!!!!!!
$headers = 'From: website form <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;
mail($emailTo, $subject, $body, $headers);
$emailSent = true;
} else {
}
}
[edit - full code, edited and (hopefully) improved]
<?php
session_start();
function clean_for_email( $inbound )
{
return str_replace( array( "\n", "\r" ), "", $inbound );
}
// I really like the name of this function. :D
function outputInput( $name, $required )
{
$attribs[] = "name=\"{$name}\"";
$attribs[] = "id=\"{$name}\"";
$attribs[] = $required?'class="required"':'';
$attribs[] = 'type="text"';
if ( count( $_POST ) && array_key_exists( $name, $_POST ) )
{
$attribs[] = 'value="' . htmlspecialchars( $_POST[$name] ) . '"';
}
echo '<input ' . implode( ' ', $attribs ) . '>';
}
//------------------------------------------------------------------------
function outputTextarea( $name, $required, $rows = 5 )
{
$attribs[] = "name=\"{$name}\"";
$attribs[] = "id=\"{$name}\"";
$attribs[] = $required?'class="required"':'';
$attribs[] = 'rows="5"';
$value = '';
if ( count( $_POST ) && array_key_exists( $name, $_POST ) )
{
$value = htmlspecialchars( $_POST[$name] );
}
echo '<textarea ' . implode( ' ', $attribs ) . '>' . $value . '</textarea>';
}
// default value
$hasError = false;
$emailSent = false;
//If the form is submitted
if( count( $_POST ) && isset($_POST['submit'] ) ) {
//Check to make sure that the name field is not empty
if(trim($_POST['name']) == '') {
$hasError = true;
} else {
$name = trim($_POST['name']);
}
//Check to make sure that the subject field is not empty
if(trim($_POST['subject']) == '') {
$hasError = true;
} else {
$subject = trim($_POST['subject']);
}
//Check to make sure sure that a valid email address is submitted
if(trim($_POST['email']) == '') {
$hasError = true;
} else if ( ! preg_match( '/^.+#.+$/i', trim( $_POST['email'] ) ) ) {
$hasError = true;
} else {
$email = trim($_POST['email']);
}
//Check to make sure comments were entered
if( trim($_POST['message']) == '') {
$hasError = true;
} else {
if(function_exists('stripslashes')) {
$message = stripslashes(trim($_POST['message']));
} else {
$message = trim($_POST['message']);
}
}
if ( ! array_key_exists( 'captcha', $_POST ) || $_SESSION['captcha'] != $_POST["captcha"] ) {
$hasError = true;
}
if( ! $hasError )
{
$captchaValid = true;
//If there is no error, send the email
if( $hasError == false ) {
$emailTo = 'xxx'; //Put your own email address here
$body = "Name: $name \n\nEmail: $email \n\nSubject: $subject \n\nMessage:\n $message";
$headers = 'From: website form <'.clean_for_email( $emailTo ).'>' . "\r\n" . 'Reply-To: ' . clean_for_email( $email );
mail($emailTo, $subject, $body, $headers);
$emailSent = true;
} else {
}
}
}
?>
<? if( $hasError ) : ?>
<p class="error">Please check if you've filled all the fields with valid information Thank you.</p>
<? endif; ?>
<? if( $emailSent == true) : ?>
<p><strong>Email Successfully Sent!</strong></p>
<p>Thank you <strong><?php echo $name;?></strong> for contacting us. Your email was successfully sent and we will be in touch with you soon.</p>
<? endif; ?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" id="contactform">
<div>
<p>
<label for="name">Name</label><br />
<? outputInput( 'name', true ); ?>
</p>
</div>
<div>
<p>
<label for="email">Email</label><br />
<? outputInput( 'email', true ); ?>
</p>
</div>
<div>
<p>
<label for="subject">Subject</label><br />
<? outputInput( 'subject', true ); ?>
</p>
</div>
<div style="margin-bottom:25px;">
<p>
<label for="message">Message</label><br />
<? outputTextarea( 'message', true ); ?>
</p>
</div>
<div style="margin-bottom:25px;">
<img src="captcha.php" alt="captcha image">
<p>
<label for="captcha">(antispam code, 3 black symbols)</label><br />
<? outputInput( 'captcha', true ); ?>
</p>
</div>
<input type="submit" value="Send Message" name="submit" />
</form>
if(isset($_POST["captcha"]))
You're missing a bracket.
Edited to show entire code.... Brackets added for captcha conditionals which were missing. As is, your code did not check if the captcha was set via post. It was only checking the session variable against the post variable. If both were blank, the form would mail. You may still have issues with captcha.php or the session variable.
<?php
//If the form is submitted
if(isset($_POST['submit'])) {
//Check to make sure that the name field is not empty
if(trim($_POST['name']) == '') {
$hasError = true;
} else {
$name = trim($_POST['name']);
}
//Check to make sure that the subject field is not empty
if(trim($_POST['subject']) == '') {
$hasError = true;
} else {
$subject = trim($_POST['subject']);
}
//Check to make sure sure that a valid email address is submitted
if(trim($_POST['email']) == '') {
$hasError = true;
} else if (!eregi("^[A-Z0-9._%-]+#[A-Z0-9._%-]+\.[A-Z]{2,4}$", trim($_POST['email'])))
{
$hasError = true;
} else {
$email = trim($_POST['email']);
}
//Check to make sure comments were entered
if(trim($_POST['message']) == '') {
$hasError = true;
} else {
if(function_exists('stripslashes')) {
$message = stripslashes(trim($_POST['message']));
} else {
$message = trim($_POST['message']);
}
}
/*captcha 2*/
if(isset($_POST["captcha"])) {
if($_SESSION["captcha"]==$_POST["captcha"])
{
//CAPTHCA is valid; proceed the message: save to database, send by e-mail ...
//If there is no error, send the email
if(!isset($hasError)) {
$emailTo = 'enquiries#sjbprojects.com'; //Put your own email address here
$emailTo = 'sjbullen#gmail.com'; //Put your own email address here
$body = "Name: $name \n\nEmail: $email \n\nSubject: $subject \n\nMessage:\n $message";
$headers = 'From: SJB Projects website form <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;
mail($emailTo, $subject, $body, $headers);
$emailSent = true;
}
else
{
echo 'CAPTHCA is not valid; ignore submission';
}
}
} else {
///message here if CAPTCHA is not set (via post)
}
}
?>
<?php if(isset($hasError)) { //If errors are found ?>
<p class="error">Please check if you've filled all the fields with valid information. Thank you.</p>
<?php } ?>
<?php if(isset($emailSent) && $emailSent == true) { //If email is sent ?>
<p><strong>Email Successfully Sent!</strong></p>
<p>Thank you <strong><?php echo $name;?></strong> for contacting SJB Projects. Your email was successfully sent and we will be in touch with you soon.</p>
<?php } ?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" id="contactform">
<div>
<p>
<label for="name">Name</label><br />
<input type="text" name="name" value="" id="name" class="required">
</p>
</div>
<div>
<p>
<label for="email">Email</label><br />
<input type="text" name="email" value="" id="email" class="required">
</p>
</div>
<div>
<p>
<label for="subject">Subject</label><br />
<input type="text" name="subject" value="" id="subject" class="required">
</p>
</div>
<div style="margin-bottom:25px;">
<p>
<label for="message">Message</label><br />
<textarea rows="5" name="message" value="" id="message" class="required"></textarea>
</p>
</div>
<div style="margin-bottom:25px;">
<img src="captcha.php" alt="captcha image">
<p>
<label for="captcha">(antispam code, 3 black symbols)</label><br />
<input type="text" name="captcha" maxlength="3" id="captcha" class="required">
</p>
</div>
<input type="submit" value="Send Message" name="submit" />
</form>
Related
I'm making a form using PHP and HTML. I want the form to use a predetermined value if the user does not fill out the form.
Default value:
Name: Jhon
Email: #example.com
Message: Without message
This is the PHP code that I use to process data:
if(isset($_POST['submitted'])) {
if(trim($_POST['contactName']) === '') {
$nameError = 'Please enter your name.';
$hasError = true;
} else {
$name = trim($_POST['contactName']);
}
if(trim($_POST['email']) === '') {
$emailError = 'Please enter your email address.';
$hasError = true;
} else if (!preg_match("/^[[:alnum:]][a-z0-9_.-]*#[a-z0-9.-]+\.[a-z]{2,4}$/i", trim($_POST['email']))) {
$emailError = 'You entered an invalid email address.';
$hasError = true;
} else {
$email = trim($_POST['email']);
}
if(trim($_POST['comments']) === '') {
$commentError = 'Please enter a message.';
$hasError = true;
} else {
if(function_exists('stripslashes')) {
$comments = stripslashes(trim($_POST['comments']));
} else {
$comments = trim($_POST['comments']);
}
}
if(!isset($hasError)) {
$emailTo = get_option('tz_email');
if (!isset($emailTo) || ($emailTo == '') ){
$emailTo = get_option('admin_email');
}
$subject = '[PHP Snippets] From '.$name;
$body = "Name: $name \n\nEmail: $email \n\nComments: $comments";
$headers = 'From: '.$name.' <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;
wp_mail($emailTo, $subject, $body, $headers);
$emailSent = true;
}
}
And here is the HTML I used:
<?php if(isset($emailSent) && $emailSent == true) { ?>
<div class="thanks">
<p>Thanks, your email was sent successfully.</p>
</div>
<?php } else { ?>
<?php the_content(); ?>
<?php if(isset($hasError) || isset($captchaError)) { ?>
<p class="error">Sorry, an error occured.<p>
<?php } ?>
<form action="<?php the_permalink(); ?>" id="contactForm" method="post">
<ul class="contactform">
<li>
<label for="contactName">Name:</label>
<input type="text" name="contactName" id="contactName" value="<?php if(isset($_POST['contactName'])) echo $_POST['contactName'];?>" class="required requiredField" />
<?php if($nameError != '') { ?>
<span class="error"><?=$nameError;?></span>
<?php } ?>
</li>
<li>
<label for="email">Email</label>
<input type="text" name="email" id="email" value="<?php if(isset($_POST['email'])) echo $_POST['email'];?>" class="required requiredField email" />
<?php if($emailError != '') { ?>
<span class="error"><?=$emailError;?></span>
<?php } ?>
</li>
<li><label for="commentsText">Message:</label>
<textarea name="comments" id="commentsText" rows="20" cols="30" class="required requiredField"><?php if(isset($_POST['comments'])) { if(function_exists('stripslashes')) { echo stripslashes($_POST['comments']); } else { echo $_POST['comments']; } } ?></textarea>
<?php if($commentError != '') { ?>
<span class="error"><?=$commentError;?></span>
<?php } ?>
</li>
<li>
<input type="submit">Send email</input>
</li>
</ul>
<input type="hidden" name="submitted" id="submitted" value="true" />
</form>
<?php } ?>
How do I make the values sent use the default values if the user does not fill out the form?
use ?: ( Ternary Operator)
$email = $_POST['email'] ?: 'default Email';
The above is identical to this if/else statement
if (empty($_POST['email'])) {
$email = 'default Email';
} else {
$email = $_POST['email'];
}
use this logic for those element you want to set a default value.
You can use the ?? operator:
$email = $_POST['email'] ?? 'defaultemail#example.com';
It's the equivalent to doing a empty() and assigning the default value if it is empty:
$email = NULL;
if (!empty($_POST['email'])) {
$email = $_POST['email'];
} else {
$email = 'defaultemail#example.com';
}
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>
There must be thousands of questions asked about PHP email scripts but I still haven't found my answer. I looked on the php website but it didn't really help either.
Basically my script validates the inputs and displays error message accordingly but when I add the second part of the script to handle the sending of the email the page displays a 500 error. Here is my code. The email hasn't been set to the correct email at the moment but I know that's not the problem.
<?php include('includes/header.php');
$yourEmail = "hello#example.com";
$formSubject = "Message recieved from enquiry form";
if( isset( $_POST["submit"])) {
//Validate the data
function validateFormData( $formData ) {
$formData = trim( stripslashes(htmlspecialchars( $formData )));
return $formData;
}
//check to see if inputs are empty
// create variables with form data
// wrap the data with our function
if( !$_POST['name']) {
$nameError = "Please enter your name <br />";
} else {
$name = validateFormData( $_POST["name"]);
}
if( !$_POST['email'] || !preg_match("/^\S+#\S+$/", $email)) {
$emailError = "Please enter a valid email address <br />";
} else {
$email = validateFormData( $_POST["email"]);
}
if( !$_POST['enquiry']) {
$enquiryError = "Please enter your enquiry <br />";
} else {
$enquiry = validateFormData( $_POST["enquiry"]);
}
Code Works fine up until this point;
//Check to see if submit is set
//Check to make sure errors don't exist
//Send the email
// Redirect user to success.html
if ( isset( $_POST["submit"]) && (empty($emailError, $nameError, $enquiryError))) {
$to = $yourEmail;
$subject = $formSubject;
$headers = 'From:'. $name . "\r\n".
'Reply-To: '. $email . "\r\n".
'X-Mailer: PHP/' . phpversion();
$body =
'The person that contacted you was '.$name.'
Email: '.$email.'
URL: '.$url.'
Message: '.$enquiry.''.
mail($yourEmail, $formSubject, $body, $headers);
header("Location: success.html");
}
}
?>
This is the HTML form, which I'm sure is alright considering the PHP works up until a certain point and displays the error messages correctly. I know I have PHP_SELF which a lot of people say not to use but I want to to stay on the page if errors exist and only redirect if email has sent.
<form id="contactForm" method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<label for="name">Name <span class="asterisk">*</span></label>
<input type="text" name="name" id="name" value="<?php echo $name;?>"tabindex="1"/>
<span class="error"><?php echo $nameError; ?></span>
<label for="email">Email <span class="asterisk">*</span></label>
<input type="email" name="email" id="email" value="<?php echo $email;?>" tabindex="2"/>
<span class="error"><?php echo $emailError; ?></span>
<span class="error"><?php echo $emailValidError; ?></span>
<label for="url">Website</label>
<input type="url" name="url" id="url" value="<?php echo $url;?>" tabindex="3"/>
<h3>Tell us about your project </h3><br />
<textarea name="enquiry" id="enquiry" tabindex="4"><?php echo $enquiry;?></textarea>
<span class="error"><?php echo $enquiryError; ?></span>
<button type="submit" id="submit" name="submit" value="submit" >Submit</button>
</form>
Your problem is here:
empty($emailError, $nameError, $enquiryError)
empty accepts only one param, you are passing it 3. Change the conditional to:
if( isset( $_POST["submit"]) && ( empty($emailError) && empty($nameError) && empty($enquiryError) ))
Or if you want to shorten that conditional a little
$Errors = $emailError.$nameError.$enquiryError;
if( isset( $_POST["submit"] ) && empty( $Errors ) )
This is why there's an error. First syntax error and then (empty($emailError, $nameError, $enquiryError)) is not a good idea. I would do something like this:
$err=0;
if( !$_POST['name']) {
$nameError = "Please enter your name <br />";
$err++;
} else {
$name = validateFormData( $_POST["name"]);
$err++;
}
if( !$_POST['email'] || !preg_match("/^\S+#\S+$/", $email)) {
$emailError = "Please enter a valid email address <br />";
$err++;
} else {
$email = validateFormData( $_POST["email"]);
}
if( !$_POST['enquiry']) {
$enquiryError = "Please enter your enquiry <br />";
$err++;
} else {
$enquiry = validateFormData( $_POST["enquiry"]);
}
if ( isset( $_POST["submit"]) && $err==0) {
//your code here//
//and i would do like this//
$result_mail_send = mail($yourEmail, $formSubject, $body, $headers);
if($result_mail_send==true){
//redirect to success
}else{
//redirect to fail//
}
}
So I have a HTML form with some PHP but I'm not getting any email whatsoever after submitting it. I can't find the problem! can you help me out?
Tried changing the if(isset($_POST['submit'])) { to 'enviar' but still not working.
tried putting some echos to see where it's not working. the only statement that is stopping at the else statement is stripslashes.
The form snippet:
<div id="contact-wrapper">
<?php if(isset($hasError)) { //If errors are found ?>
<p class="error">Please check if you entered valid information.</p>
<?php } ?>
<?php if(isset($emailSent) && $emailSent == true) { //If email is sent ?>
<p><strong>Email sent with success!</strong></p>
<p>Thank you for using our contact form <strong><?php echo $name;?></strong>, we will contact you soon.</p>
<?php } ?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" id="contactform">
<div>
<label for="name"><strong>Name:</strong></label>
<input type="text" size="50" name="contactname" id="contactname" value="" class="required" />
</div>
<div>
<label for="email"><strong>E-mail:</strong></label>
<input type="text" size="50" name="email" id="email" value="" class="required email" />
</div>
<div>
<label for="subject"><strong>Subject:</strong></label>
<input type="text" size="50" name="subject" id="subject" value="" class="required" />
</div>
<div>
<label for="message"><strong>Message:</strong></label>
<textarea rows="5" cols="50" name="message" id="message" class="required"></textarea>
</div>
<input type="submit" value="enviar" name="submit" id="submit" />
</form>
</div>
and the PHP:
<?php
//If the form is submitted
if(isset($_POST['submit'])) {
//Check to make sure that the name field is not empty
if(trim($_POST['contactname']) == '') {
$hasError = true;
} else {
$name = trim($_POST['contactname']);
}
//Check to make sure that the subject field is not empty
if(trim($_POST['subject']) == '') {
$hasError = true;
} else {
$subject = trim($_POST['subject']);
}
//Check to make sure sure that a valid email address is submitted
if(trim($_POST['email']) == '') {
$hasError = true;
} else if (!eregi("^[A-Z0-9._%-]+#[A-Z0-9._%-]+\.[A-Z]{2,4}$", trim($_POST['email']))) {
$hasError = true;
} else {
$email = trim($_POST['email']);
}
//Check to make sure comments were entered
if(trim($_POST['message']) == '') {
$hasError = true;
} else {
if(function_exists('stripslashes')) {
$comments = stripslashes(trim($_POST['message']));
} else {
$comments = trim($_POST['message']);
}
}
//If there is no error, send the email
if(!isset($hasError)) {
$emailTo = 'myemail#email.com'; //Put your own email address here
$body = "Name: $name \n\nEmail: $email \n\nSubject: $subject \n\nComments:\n $comments";
$headers = 'From: My Site <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;
mail($emailTo, $subject, $body, $headers);
$emailSent = true;
}
}
?>
Before getting any email, you have to be sure the email is being sent.
$sent = mail($emailTo, $subject, $body, $headers);
var_dump($sent);
What does this code output when placed in the appropriate place?
Have you tried a simple php page to do a test Email (eg fixed content) and I assume the webserver has email configured and is prepared to relay for your address?
If this is WordPress contact form, for starters:
mail($emailTo, $subject, $body, $headers);
should be:
wp_mail($emailTo, $subject, $body, $headers);
See: wp_mail codex
Now you have to check your e-mail setup, as well as WordPress e-mail setup too.
I have a form which does everything right except send the input values to my email, what am I doing wrong? Ps: not using local server, so that's not it.
EDIT: I'm not getting any email whatsoever.
Tried changing the if(isset($_POST['enviar'])) { part but still not working.
Tried the chatty echos. the only if statement that isn't behaving properly is stripslashes. It stops at the else statement.
The form snippet:
<div id="contact-wrapper">
<?php if(isset($hasError)) { //If errors are found ?>
<p class="error">Please check if you entered valid information.</p>
<?php } ?>
<?php if(isset($emailSent) && $emailSent == true) { //If email is sent ?>
<p><strong>Email sent with success!</strong></p>
<p>Thank you for using our contact form <strong><?php echo $name;?></strong>, we will contact you soon.</p>
<?php } ?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" id="contactform">
<div>
<label for="name"><strong>Name:</strong></label>
<input type="text" size="50" name="contactname" id="contactname" value="" class="required" />
</div>
<div>
<label for="email"><strong>E-mail:</strong></label>
<input type="text" size="50" name="email" id="email" value="" class="required email" />
</div>
<div>
<label for="subject"><strong>Subject:</strong></label>
<input type="text" size="50" name="subject" id="subject" value="" class="required" />
</div>
<div>
<label for="message"><strong>Message:</strong></label>
<textarea rows="5" cols="50" name="message" id="message" class="required"></textarea>
</div>
<input type="submit" value="enviar" name="submit" id="submit" />
</form>
</div>
and the PHP:
<?php
//If the form is submitted
if(isset($_POST['submit'])) {
//Check to make sure that the name field is not empty
if(trim($_POST['contactname']) == '') {
$hasError = true;
} else {
$name = trim($_POST['contactname']);
}
//Check to make sure that the subject field is not empty
if(trim($_POST['subject']) == '') {
$hasError = true;
} else {
$subject = trim($_POST['subject']);
}
//Check to make sure sure that a valid email address is submitted
if(trim($_POST['email']) == '') {
$hasError = true;
} else if (!eregi("^[A-Z0-9._%-]+#[A-Z0-9._%-]+\.[A-Z]{2,4}$", trim($_POST['email']))) {
$hasError = true;
} else {
$email = trim($_POST['email']);
}
//Check to make sure comments were entered
if(trim($_POST['message']) == '') {
$hasError = true;
} else {
if(function_exists('stripslashes')) {
$comments = stripslashes(trim($_POST['message']));
} else {
$comments = trim($_POST['message']);
}
}
//If there is no error, send the email
if(!isset($hasError)) {
$emailTo = 'myemail#email.com'; //Put your own email address here
$body = "Name: $name \n\nEmail: $email \n\nSubject: $subject \n\nComments:\n $comments";
$headers = 'From: My Site <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;
mail($emailTo, $subject, $body, $headers);
$emailSent = true;
}
}
?>
The ereg() family of functions are deprecated. use the preg_...() equivalents instead. They work almost exactly the same, except requiring delimiters around the match patterns.
As well, don't use PHP_SELF in your form. That value is raw user-supplied data and can be trivially subverted for an XSS attack.
Checking for a particular form field to see if a POST occured is somewhat unreliable - you might change the field's name later on and your check will fail. However, this
if ($_SERVER['REQUEST_METHOD'] == 'POST) { ... }
will always work, no matter how many or few fields are in the form, as long as the form was actually POSTed.
As for the actual problem, I'm assuming the mail is getting sent out, or you'd have complained about that. That means your variables aren't being populated properly. Instead of just sending the mail, echo out the various variables as they're built, something like:
echo 'Checking name';
if ($_POST['name'] .....) {
echo 'name is blank';
} else {
$name = ...;
echo "Found name=$name";
}
Basically have your code become extremely "chatty" and tell you what it's doing at each stage.
#dafz: Change
if(isset($_POST['submit'])) {
to
if(isset($_POST['enviar'])) {
#Marc B deserves another up-vote for his answer as well.
Edit
You can try the following update.
if(!isset($hasError)) {
$siteAddress = 'validaddress#yourdomain.com'; //Put admin# or info# your domain here
$emailTo = 'myemail#email.com'; //Put your own email address here
$body = "Name: $name \r\nEmail: $email \r\nSubject: $subject \r\nComments: $comments \r\n";
$headers = 'To: ' . $name . ' <' . $emailTo . '>' . "\r\n";
$headers .= 'From: My Site <' . $siteAddress . '>' . "\r\n";
$headers .= 'Reply-To: ' . $email . "\r\n";
if (mail($emailTo, $subject, $body, $headers)) {
$emailSent = true;
} else {
$emailSent = false;
}
}