I have an issue with a contact form I have set up on a clients site, the form posts to my email address no problem but doesn't for my client who's domain is registered through 123 reg and email accounts are set up within Gmail. On contacting my web host they have suggested using SMTP, this is something I have never used before, I have googled this but haven't came to any light. Anyone have any ideas?
Thanks,
Melissa
<?php
if (array_key_exists('submit', $_POST)) {
$to = 'hello#email.co.uk'; //change this to suit your admin email address
$subject = 'Website enquiry'; //change this to the mail subject you want the admin to receive
$expected = array('name', 'email', 'tel', 'message1'); //list all of the fields in the form
$required = array('name', 'email', 'message1'); //list the required fields in the form
$missing = array();
$suspect = false;
$pattern = '/Content-Type:|Bcc:|Cc:/i';
function isSuspect($val, $pattern, &$suspect) {
if (is_array($val)) {
foreach ($val as $item) {
isSuspect($item, $pattern, $suspect);
}
}
else {
if (preg_match($pattern, $val)) {
$suspect = true;
}
}
}
isSuspect($_POST, $pattern, $suspect);
if ($suspect) {
$mailSent = false;
unset($missing);
}
else {
foreach ($_POST as $key => $value) {
$temp = is_array($value) ? $value : trim($value);
if (empty($temp) && in_array($key, $required)) {
array_push($missing, $key);
}
elseif (in_array($key, $expected)) {
${$key} = $temp;
}
}
}
if (!empty($email)) {
$checkEmail = '/^[^#]+#[^\s\r\n\'";,#%]+$/';
if (!preg_match($checkEmail, $email)) {
array_push($missing, 'email');
}
}
if (!$suspect && empty($missing)) {
$message .= "Name: $name\n\n";
$message .= "Email address: $email\n\n";
$message .= "Telephone number: $tel\n\n";
$message .= "Message: $message1\n\n";
$message = wordwrap($message, 70);
$additionalHeaders = "From: $email";
$complete = mail($to, $subject, $message, $additionalHeaders);
if ($complete) {
unset($missing);
}
}
}
?>
Below shows the form:
<?php
if ($_POST && isset($missing)) {
echo'<p class="warning">Please complete the missing or incorrect fields.</p>';
}
if ($_POST && isset($complete)) {
echo '<p class="green"><strong>Thank you for contacting us. We will be in touch soon.</strong></p>';
}
else{?>
<form method="post" action="" id="contact_form" class="validate">
<fieldset>
<legend>Your Details</legend>
<label for="name"><b>Full Name</b></label>
<input name="name" placeholder="John Smith" class="" <?php if (isset($missing)) {echo 'value="'.htmlentities($_POST['name']).'"';} ?> />
<br>
<label for="email"><b>Email Address</b></label>
<input type="email" name="email" placeholder="hello#shnuggle.com" class="" <?php if (isset($missing)) {echo 'value="'.htmlentities($_POST['email']).'"';} ?> />
<br>
<label for="phone"><b>Phone Number <span class="note">(optional)</span></b></label>
<input type="tel" name="tel" placeholder="+44 (0)28 9012 3456" class="" <?php if (isset($missing)) {echo 'value="'.htmlentities($_POST['tel']).'"';} ?> />
<br>
<legend>Your Message</legend>
<textarea name="message1" <?php if (isset($missing)) {echo 'value="'.htmlentities($_POST['message1']).'"';} ?> />Hello,</textarea>
</fieldset>
<!--<button type="submit" class="btn submit"><span class="icon">m</span> Send Message</button>-->
<input type="submit" class="btn" name="submit" value="Send Message" />
<button type="reset" class="btn reset">Clear form</button>
</form>
<?php }?>
It's Work !!
If you got Error undefined Variable on 54 line
than convert
$message .= "Name: $name\n\n";
to
$message = "Name: $name\n\n";
Related
With purpose to save your time I have two screenshots of my contact form.
Also instead of expected result the message "Thank you. Your message has been received" I got in new window. How can I place the message in that input element? Where am I wrong?
You can check my contact form by this link just send any message.
Thank you so much for your time and answers.
<form action="contact/form-handler.php" method="post">
<fieldset>
<div class="form-row">
<div class="form-group col-md-6">
<input type="text" class="form-control" name="name" id="name" placeholder="Your Name"/>
</div>
<div class="form-group col-md-6">
<input type="text" class="form-control" name="email" id="email" placeholder="Your Email"/>
</div>
</div>
<div class="form-group">
<input type="text" class="form-control" name="subject" id="subject" placeholder="Subject"/>
</div>
<div class="form-group">
<textarea class="form-control" name="message" rows="5" data-rule="required" data-msg="Please write something for us" placeholder="Message"></textarea>
</div>
<div>
<input type="hidden" name="hidden" value="" />
<div class="nocomment">
<label for="nocomment"></label>
<input id="nocomment" class="nocomment" value="" name="nocomment" />
</div>
<div class="text-center">
<input type="submit" value="Send Message" name="submit"/>
<input type="reset" value="Clear Message" name="reset"/>
</div>
</div>
<input type="hidden" name="v_error" id="v-error" value="Required" />
<input type="hidden" name="v_email" id="v-email" value="Enter a valid email" />
</fieldset>
</form>
And my contact/form-handler.php
<?php
include('SMTPClass.php');
$emailto = 'myemail.com';
// retrieve from parameters
$emailfrom = isset($_POST["email"]) ? $_POST["email"] : "";
$nocomment = isset($_POST["nocomment"]) ? $_POST["nocomment"] : "";
$subject = 'Email from InWebWorld';
$message = '';
$response = '';
$response_fail = 'There was an error verifying your details.';
// Honeypot captcha
if($nocomment == '') {
$params = $_POST;
foreach ( $params as $key=>$value ){
if(!($key == 'ip' || $key == 'emailsubject' || $key == 'url' || $key == 'emailto' || $key == 'nocomment' || $key == 'v_error' || $key == 'v_email')){
$key = ucwords(str_replace("-", " ", $key));
if ( gettype( $value ) == "array" ){
$message .= "$key: \n";
foreach ( $value as $two_dim_value )
$message .= "...$two_dim_value<br>";
}else {
$message .= $value != '' ? "$key: $value\n" : '';
}
}
}
$response = sendEmail($subject, $message, $emailto, $emailfrom);
} else {
$response = $response_fail;
}
echo $response;
// Run server-side validation
function sendEmail($subject, $content, $emailto, $emailfrom) {
$from = $emailfrom;
$response_sent = 'Thank you. Your messsage has been received.';
$response_error = 'Error. Please try again.';
$subject = filter($subject);
$url = "Origin Page: ".$_SERVER['HTTP_REFERER'];
$ip = "IP Address: ".$_SERVER["REMOTE_ADDR"];
$message = $content."\n$ip\r\n$url";
// Validate return email & inform admin
$emailto = filter($emailto);
// Setup final message
$body = wordwrap($message);
// Create header
$headers = "From: $from\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/plain; charset=utf-8\r\n";
$headers .= "Content-Transfer-Encoding: quoted-printable\r\n";
// Send email
$mail_sent = #mail($emailto, $subject, $body, $headers);
$response = $mail_sent ? $response_sent : $response_error;
return $response;
}
// Remove any un-safe values to prevent email injection
function filter($value) {
$pattern = array("/\n/", "/\r/", "/content-type:/i", "/to:/i", "/from:/i", "/cc:/i");
$value = preg_replace($pattern, "", $value);
return $value;
}
exit;
?>
If this php code is in contact/form-handler.php than instead of echo $response; you should redirect back to your contact page with the message, like header('Location: contact_page_url?message='.urlencode($response));And in your contact page put below your form:
<script>
function findGetParameter(parameterName) {
var result = null, tmp = [];
location.search.substr(1).split("&").forEach(function (item){
tmp = item.split("=");
if (tmp[0] === parameterName)
result = decodeURIComponent(tmp[1]);
});
return result;
}
document.querySelector('#nocomment').value = findGetParameter('message') || '';
</script>
This question already has answers here:
PHP validation checkbox
(3 answers)
How to validate single checkbox in php script
(2 answers)
checkbox in PHP validation
(2 answers)
How to validate a single checkbox using PHP & MySQL
(2 answers)
PHP Checkbox Validation
(3 answers)
Closed 3 years ago.
I have a problem with validating a checkbox. I want to show error message if "submit" is clicked while checkbox is unchecked.
With the code I have right now, form gets submitted anyway. I've tried multiple code snippets I found from other questions but none seem to work..
HTML:
<?php include 'contact-form.php'; ?>
<form id="contact" action="<?php $_SERVER['PHP_SELF']; ?>" method="post"
enctype="multipart/form-data">
<h3>Add issue</h3>
<fieldset>
<input placeholder="Nimi" type="text" tabindex="1" name="thename" value="<?= $thename ?>" autofocus>
<div class="error"><span><?= $name_error ?></span></div>
</fieldset>
<fieldset>
<input placeholder="Email" type="text" tabindex="2" name="email" value="<?= $email ?>">
<div class="error"><span><?= $email_error ?></span></div>
</fieldset>
<fieldset>
<input type="checkbox" name="checkbox1" value="yes"/> Annan ühendusele loa minu eluloo avaldamiseks siinsel kodulehel. <br>
<div class="error"><span><?= $checkbox1_error ?></span></div>
</fieldset>
</form>
PHP:
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["thename"])) {
$name_error = "Palun sisesta nimi";
} else {
$thename = test_input($_POST["thename"]);
// check if name only contains letters, whitespace and hyphen
if (!preg_match("/^[a-zA-Z -]*$/",$thename)) {
$name_error = "Sisestada saab ainult tähti, tühikuid ja sidekriipse";
}
}
if (empty($_POST["email"])) {
$email_error = "Palun sisesta email";
} else {
$email = test_input($_POST["email"]);
// email validation
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$email_error = "Sisesta email korrektselt";
}
}
if(!isset($_POST['checkbox1'])) {
//checkbox is not checked
$checkbox1_error = 'Väli peab olema kinnitatud';
}
if ($name_error == '' and $email_error == '' and $message_error == '' and $attachment_error == '' and $checkbox1_error == ''){
$message_body = '';
unset($_POST['submit']);
foreach ($_POST as $key => $value){
$message_body .= "$key: $value\n";
}
$to = 'myemail#gmail.com';
$subject = 'My subject';
$message = "My message";
if (#mail($to, '=?UTF-8?B?' . base64_encode($subject) . '?=', $datamsg, $headers, "-f$email")){
$success = "Aitäh, kiri edukalt saadetud!";
} else {
$error = "Saatmine ebaõnnestus. Palun proovige uuesti.";
}
Any help is appreciated!
I used this code and its showing the error message for checkbox
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["thename"])) {
$name_error = "Palun sisesta nimi";
} else {
$thename = $_POST["thename"];
// check if name only contains letters, whitespace and hyphen
if (!preg_match("/^[a-zA-Z -]*$/", $thename)) {
$name_error = "Sisestada saab ainult tähti, tühikuid ja sidekriipse";
}
}
if (empty($_POST["email"])) {
$email_error = "Palun sisesta email";
} else {
$email = $_POST["email"];
// email validation
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$email_error = "Sisesta email korrektselt";
}
}
if (!isset($_POST['checkbox1'])) {
//checkbox is not checked
$checkbox1_error = 'Väli peab olema kinnitatud';
}
if (!isset($name_error) and ! isset($email_error) and ! isset($message_error) and ! isset($attachment_error) and ! isset($checkbox1_error)) {
$message_body = '';
unset($_POST['submit']);
foreach ($_POST as $key => $value) {
$message_body .= "$key: $value\n";
}
$to = 'myemail#gmail.com';
$subject = 'My subject';
$message = "My message";
if (#mail($to, '=?UTF-8?B?' . base64_encode($subject) . '?=', $datamsg, $headers, "-f$email")) {
$success = "Aitäh, kiri edukalt saadetud!";
} else {
$error = "Saatmine ebaõnnestus. Palun proovige uuesti.";
}
}
}
?>
<form id="contact" action="<?php $_SERVER['PHP_SELF']; ?>" method="post"
enctype="multipart/form-data">
<h3>Add issue</h3>
<fieldset>
<input placeholder="Nimi" type="text" tabindex="1" name="thename" value="<?php echo $_POST['thename'] ?>" autofocus>
<div class="error"><span><?php echo $name_error ?></span></div>
</fieldset>
<fieldset>
<input placeholder="Email" type="text" tabindex="2" name="email" value="<?php echo $_POST['email'] ?>">
<div class="error"><span><?php echo $email_error ?></span></div>
</fieldset>
<fieldset>
<input type="checkbox" name="checkbox1" value="yes"/> Annan ühendusele loa minu eluloo avaldamiseks siinsel kodulehel. <br>
<div class="error"><span><?php echo $checkbox1_error ?></span></div>
</fieldset>
<input type="submit" value="Submit"/>
</form>
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>
Something very strange going with my contact form..
When submitting via the actual page.. www.mydomain.com/mail.php it submits fine, send the email enquiry works as it should.
However, when its included on the contact page with the following..
<?php include('mail.php'); ?>
It sends the email twice, or sometimes not at all!
Any ideas?
<?php
if (isset($_POST["mail"]) && ($_POST["mail"]=="send")) {
//ini_set("sendmail_from", "mailserver#thedomain.com");
/******** START OF CONFIG SECTION *******/
//$sendto = "enquiries#rivelintravel.co.uk";
$sendto = "test#thedomain.com";
$subject = "Website Form Test";
$errorImage = "assets/form/exclamation.png";
$acceptImage = "assets/form/accept.png";
/******** END OF CONFIG SECTION *******/
$SpamReplaceText = "*content removed*";
// Error message prited if spam form attack found
$SpamErrorMessage = "<div class=\"contactFormErrorMessage\">Malicious code content detected.<br>Your IP Number of ".getenv("REMOTE_ADDR")." has been logged.</div>";
foreach($_POST as $key => $value) {
$post[$key] = $value;
}
$name = $post['name'];
$email = $post['email'];
// $message = $post['message'];
$headers = "From: $email\n";
$headers . "MIME-Version: 1.0\n"
. "Content-Transfer-Encoding: 7bit\n"
. "Content-type: text/html; charset = \"iso-8859-1\";\n\n";
// Check for Website URL's in the form input boxes as if we block website URLs from the form,
// then this will stop the spammers wastignt ime sending emails
foreach($post as $key => $value) {
if (preg_match("/http/i", "$post[$key]")) {echo "$SpamErrorMessage"; exit();}
}
// Patterm match search to strip out the invalid charcaters, this prevents the mail injection spammer
$pattern = '/(;|\||`|>|<|&|^|"|'."\n|\r|'".'|{|}|[|]|\)|\()/i'; // build the pattern match string
foreach($post as $key => $value) {
$post[$key] = preg_replace($pattern, "", $value);
}
// Check for the injected headers from the spammer attempt
// This will replace the injection attempt text with the string you have set in the above config section
$find = array("/bcc\:/i","/Content\-Type\:/i","/cc\:/i","/to\:/i");
foreach($post as $key => $value) {
$post[$key] = preg_replace($find, "$SpamReplaceText", $value);
}
// Check to see if the fields contain any content we want to ban
foreach($post as $key => $value) {
if(stristr($post[$key], $SpamReplaceText) !== FALSE) {echo "$SpamErrorMessage"; exit();}
}
// Do a check on the send email and subject text
foreach($post as $key => $value) {
if(stristr($post[$key], $SpamReplaceText) !== FALSE) {echo "$SpamErrorMessage"; exit();}
}
// Build the email body text
$emailcontent = "Website Form Test" . "\n";
$emailcontent .= "_" . "\n";
$emailcontent .= "Name: " . $_POST['name'] . "\n";
$emailcontent .= "Email: " . $_POST['email'] . "\n";
$emailcontent .= "Telephone Number: " . $_POST['tel'] . "\n";
$emailcontent .= "_" . "\n";
// Check the email address enmtered matches the standard email address format
if (!eregi("^[A-Z0-9._%-]+#[A-Z0-9._%-]+\.[A-Z]{2,6}$", $post['email'])) {
echo "<div class=\"contactFormErrorMessage\"><img src=\"$errorImage\" alt=\"Error\" /><p>It appears you entered an invalid email address</p><p><a href='javascript: history.go(-1)'>Click here to go back</a></p></div>";
}
elseif (!trim($post['name'])) {
echo "<div class=\"contactFormErrorMessage\"><img src=\"$errorImage\" alt=\"Error\" /><p>Please go back and enter a Name</p><p><a href='javascript: history.go(-1)'>Click here to go back</a></p></div>";
}
elseif (!trim($post['email'])) {
echo "<div class=\"contactFormErrorMessage\"><img src=\"$errorImage\" alt=\"Error\" /><p>Please go back and enter an Email</p><p><a href='javascript: history.go(-1)'>Click here to go back</a></p></div>";
}
// Sends out the email or will output the error message
elseif (mail($sendto, $subject, $emailcontent, $headers)) {
echo "<div class=\"contactFormSuccessMessage\"><img src=\"$acceptImage\" alt=\"Success\" /><p>Thank You $name<br />We will be in touch as soon as possible.</p></div>";
}
}else{
?>
<form action="<?php print $_SERVER['PHP_SELF']; ?>" method="post" id="contactForm" name="contactForm">
<input name="mail" type="hidden" value="send"/>
<div class="content clearfix">
<div class="left">
<h3>Personel Details: </h3>
<div class="field">
<label for="name">Name <span class="required" title="This field is required.">*</span></label>
<input name="name" type="text" />
</div>
<div class="field">
<label for="email">Email Address<span class="required" title="This field is required.">*</span></label>
<input name="email" type="text" />
</div>
<div class="field">
<label for="tel">Contact Number</label>
<input name="tel" type="text" />
</div>
</div>
<!--column1-->
<div id="sub" class="field">
<label for="submit"> </label>
<input class="submit" type="submit" name="submit" value="submit" id"submit" />
</div>
</div>
</div><!--column-->
</fieldset>
</form>
<?php } ?>
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>