PHP, Not able to send Emails - php

I would like to have a contact form on my that requires the *fullname, *email address, and *subject and *message. I followed a tutorial to develop my form but for some reason it is not sending my test message.
I'm not experienced enough with PHP to figure out what I am doing wrong, so I am hoping to get suggestions on how to resolve this issue. All questions, suggestions, and possible solutions are welcome. Thanks.
contact form php:
Code:
<?php
// EDIT THE FOLLOWING LINE BELOW AS REQUIRED
$send_email_to = "jb#me.com";
function send_email($name,$email,$email_subject,$email_message)
{
global $send_email_to;
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
$headers .= "From: ".$email. "\r\n";
$message = "<strong>Email = </strong>".$email."<br>";
$message .= "<strong>Name = </strong>".$name."<br>";
$message .= "<strong>Message = </strong>".$email_message."<br>";
#mail($send_email_to, $email_subject, $message,$headers);
return true;
}
function validate($name,$email,$message,$subject)
{
$return_array = array();
$return_array['success'] = '1';
$return_array['name_msg'] = '';
$return_array['email_msg'] = '';
$return_array['message_msg'] = '';
$return_array['subject'] = '';
if($email == '')
{
$return_array['success'] = '0';
$return_array['email_msg'] = 'email is required';
}
else
{
$email_exp = '/^[A-Za-z0-9._%-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
if(!preg_match($email_exp,$email)) {
$return_array['success'] = '0';
$return_array['email_msg'] = 'enter valid email.';
}
}
if($name == '')
{
$return_array['success'] = '0';
$return_array['name_msg'] = 'name is required';
}
else
{
$string_exp = "/^[A-Za-z .'-]+$/";
if (!preg_match($string_exp, $name)) {
$return_array['success'] = '0';
$return_array['name_msg'] = 'enter valid name.';
}
}
if($subject == '')
{
$return_array['success'] = '0';
$return_array['subject_msg'] = 'subject is required';
}
if($message == '')
{
$return_array['success'] = '0';
$return_array['message_msg'] = 'message is required';
}
else
{
if (strlen($message) < 2) {
$return_array['success'] = '0';
$return_array['message_msg'] = 'enter valid message.';
}
}
return $return_array;
}
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$subject = $_POST['subject'];
$return_array = validate($name,$email,$message,$subject);
if($return_array['success'] == '1')
{
send_email($name,$email,$subject,$message);
}
header('Content-type: text/json');
echo json_encode($return_array);
die();
?>
Contact Form HTML:
Code:
<fieldset id="contact_form">
<div id="msgs"> </div>
<form id="cform" name="cform" method="post" action="">
<input type="text" id="name" name="name" value="Full Name*" onfocus="if(this.value == 'Full Name*') this.value = ''"
onblur="if(this.value == '') this.value = 'Full Name*'" />
<input type="text" id="email" name="email" value="Email Address*" onfocus="if(this.value == 'Email Address*') this.value = ''"
onblur="if(this.value == '') this.value = 'Email Address*'" />
<input type="text" id="subject" name="subject" value="Subject*" onfocus="if(this.value == 'Subject*') this.value = ''"
onblur="if(this.value == '') this.value = 'Subject*'" />
<textarea id="msg" name="msg" onfocus="if(this.value == 'Your Message*') this.value = ''"
onblur="if(this.value == '') this.value = 'Your Message*'">Your Message*</textarea>
<button id="submit" class="button"> Send Message</button>
</form>
</fieldset>

Your form's action isn't set to anything. You'll need to point it at the script you have there that sends the email.
Ie:
<form id.. name.. method.. action="/handle_post.php">

Set the correct action and then try it should work..
if it still does not work test it with curl utility to see if ur script is fine..
One more mistake that i saw was that ur text area form name is msg while on server ur expecting ur post request it have message. That wont work..
If u still face problem then we wd debug further :)

First you need to set action to some script that will handle $_POST inputs (contactform.php) or $_SERVER['PHP_SELF'] for the same file.
Second you should send data by input type=submit not button.

Related

PHP Multiple Validations

I'm trying to make $name, $email, and $message validate in one script without making them all look like a error (make them all a red color) rather than the one that is actually incorrect.
Her is the code I'm using:
PHP:
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$visitors_site = $_POST['site'];
$message = $_POST['message'];
$email_from = 'mattmowen1#gmail.com';
$email_subject = 'New Contact Submission';
$to = 'matt.owen#example.com';
$headers = "From:" . $email;
$headers = "Contact Submission From: " . $email;
$message1 = "Name: " . $name;
$message2 = "\n\nEmail: " . $email;
$message3 = "\n\nPhone: " . $phone;
$message4 = "\n\nTheir Site: " . $visitors_site;
$message5 = "\n\nMessage: " . $message;
$email_body = $message1 . $message2 . $message3 . $message4 . $message5;
if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
mail($to, $email_subject, $email_body,$headers);
exit(json_encode(array('error' => 0)));
} else {
exit(json_encode(array('error' => 1)));
}
if ($name == "") {
exit(json_encode(array('error' => 1)));
} else {
mail($to, $email_subject, $email_body,$headers);
exit(json_encode(array('error' => 0)));
}
?>
AJAX Script:
var sendEmail = function(){
var url = 'main.php';
$.ajax({
url : url,
type : "POST",
dataType : "JSON",
data : $('#contact-form').serialize(),
success : function(response) {
if (response.error == 0) {
$('#contact-form')[0].reset();
alert('Form submitted successfully. We will contact you asap.');
} else {
$('#email-input').css('color', 'red');
alert('ERROR MESSAGE');
}
}
})
return false;
}
HTML:
<div id="contact">
<div class="container">
<form id="contact-form" method="post" onsubmit="return sendEmail()">
<h1>Contact Form</h1>
<fieldset>
<input placeholder="Your Name" type="text" name="name" id="name-input" required value="<?php echo isset($_POST['name']) ? $_POST['name'] : ''; ?>">
</fieldset>
<fieldset>
<input placeholder="Your Email Address" type="email" name="email" id="email-input" required value="<?php echo isset($_POST['email']) ? $_POST['email'] : ''; ?>">
</fieldset>
<fieldset>
<input placeholder="Your Phone Number (optional)" type="tel" name="phone" required>
</fieldset>
<fieldset>
<input placeholder="Your Web Site (optional)" type="url" name="site" required>
</fieldset>
<fieldset>
<textarea placeholder="Type your message here...." name="message" required value="<?php echo isset($_POST['email']) ? $_POST['email'] : ''; ?>"></textarea>
</fieldset>
<fieldset>
<button type="submit" id="contact-submit" name="submit">Submit</button>
</fieldset>
</form>
</div>
</div>
Just send back a list of bad elements, instead of a blanket error statement
<?php
// ...
$errors = [];
if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
$errors[] = "email";
}
if ($name == "") {
$errors[] = "name";
}
if ($message == "") {
$errors[] = "message";
}
if (count($errors) === 0) {
mail($to, $email_subject, $email_body,$headers);
}
echo json_encode($errors);
//...
Then in your JS:
success : function(response) {
if (response.length == 0) {
$('#contact-form')[0].reset();
alert('Form submitted successfully. We will contact you asap.');
} else {
for (var i = 0; i < response.length; i++) {
$('#' + response[i] + '-input').css('color', 'red');
alert('ERROR MESSAGE');
}
}
}
My Javascript is a bit rusty but that should do the trick.
Note that <textarea> doesn't have a value attribute, contents are added as a child text node. You should also use htmlspecialchars() on all output from PHP to prevent XSS problems.
in your js:
$erro = 0;
if(document.getElementById("name-input").value == null or document.getElementById("name-input").value == ""){
$erro = 1;
document.getElementById("name-input").style.borderColor = "red";
}
if(document.getElementById("email-input").value == null or document.getElementById("email-input").value == ""){
$erro = 1;
document.getElementById("email-input").style.borderColor = "red";
}
...
if($erro == 0){
//run ajax
}
You can put a bit more html code to make a hidden textbox appear using.
if(document.getElementById("email-input").value == null or document.getElementById("email-input").value == ""){
$erro = 1;
document.getElementById("email-input").style.borderColor = "red";
document.getElementById("id_erro1").style.visibility = "visible";
}
create in your html:
<fieldset>
<input placeholder="Your Email Address" type="email" name="email" id="email-input" required value="<?php echo isset($_POST['email']) ? $_POST['email'] : ''; ?>">
<input type="hidden" name="error_mensage1" id="id_erro1" value="Required field" >
</fieldset>
Use css to Spice up.

Validation Form is not working

My validation contact form is not working. While I try to submit the form the following error occurs:
Warning: mail() [function.mail]: Failed to connect to mailserver at
"localhost" port 25, verify your "SMTP" and "smtp_port" setting in
php.ini or use ini_set() in
E:\CMS_Site\wamp\www\sitename\contents\send_mail.php on line 53
<?php
require_once 'mandrill-api-php/src/Mandrill.php'; //Not required with Composer
$mandrill = new Mandrill('eWTy3pUA1Okb-4lwUtk4dg');
if(isset($_POST['name']) != NULL && isset($_POST['email']) != NULL && isset($_POST['message']) != NULL )
{ // if(isset($_POST['submit_form']) != NULL) IF START
$name = strtoupper (trim($_POST['name']));
$address = trim($_POST['address']);
$email = strtolower(trim($_POST['email']));
$contact = trim($_POST['contact']);
$country = trim($_POST['country']);
$website = trim($_POST['website']);
$subject = trim($_POST['subject']);
$message = trim($_POST['message']);
//---------------------------------------------
error_reporting(E_ALL ^ E_NOTICE);
$my_email = "kiranpahadi#gmail.com";
$errors = array();
// Remove $_COOKIE elements from $_REQUEST.
if(count($_COOKIE)){foreach(array_keys($_COOKIE) as $value){unset($_REQUEST[$value]);}}
// Validate email field.
if(isset($_REQUEST['email']) && !empty($_REQUEST['email']))
{
$_REQUEST['email'] = trim($_REQUEST['email']);
if(substr_count($_REQUEST['email'],"#") != 1 || stristr($_REQUEST['email']," ") || stristr($_REQUEST['email'],"\\") || stristr($_REQUEST['email'],":")){$errors[] = "Email address is invalid";}else{$exploded_email = explode("#",$_REQUEST['email']);if(empty($exploded_email[0]) || strlen($exploded_email[0]) > 64 || empty($exploded_email[1])){$errors[] = "Email address is invalid";}else{if(substr_count($exploded_email[1],".") == 0){$errors[] = "Email address is invalid";}else{$exploded_domain = explode(".",$exploded_email[1]);if(in_array("",$exploded_domain)){$errors[] = "Email address is invalid";}else{foreach($exploded_domain as $value){if(strlen($value) > 63 || !preg_match('/^[a-z0-9-]+$/i',$value)){$errors[] = "Email address is invalid"; break;}}}}}}
}
// Check referrer is from same site.
if(!(isset($_SERVER['HTTP_REFERER']) && !empty($_SERVER['HTTP_REFERER']) && stristr($_SERVER['HTTP_REFERER'],$_SERVER['HTTP_HOST']))){$errors[] = "You must enable referrer logging to use the form";}
// Check for a blank form.
function recursive_array_check_blank($element_value)
{
global $set;
if(!is_array($element_value)){if(!empty($element_value)){$set = 1;}}
else
{
foreach($element_value as $value){if($set){break;} recursive_array_check_blank($value);}
}
}
recursive_array_check_blank($_REQUEST);
if(!$set){$errors[] = "You cannot send a blank form";}
unset($set);
// Display any errors and exit if errors exist.
if(count($errors)){foreach($errors as $value){print "$value<br>";} exit;}
if(!defined("PHP_EOL")){define("PHP_EOL", strtoupper(substr(PHP_OS,0,3) == "WIN") ? "\r\n" : "\n");}
// Build message.
function build_message($request_input){if(!isset($message_output)){$message_output ="";}if(!is_array($request_input)){$message_output = $request_input;}else{foreach($request_input as $key => $value){if(!empty($value)){if(!is_numeric($key)){$message_output .= str_replace("_"," ",ucfirst($key)).": ".build_message($value).PHP_EOL.PHP_EOL;}else{$message_output .= build_message($value).", ";}}}}return rtrim($message_output,", ");}
$message = build_message($_REQUEST);
$message = $message . PHP_EOL.PHP_EOL."-- ".PHP_EOL."The Message has been submitted successfully ";
$message = stripslashes($message);
$subject = stripslashes($subject);
if($email)
{
$headers = "From: {$name} <{$_REQUEST['email']}>";
$headers .= PHP_EOL;
$headers .= "Reply-To: " . $_REQUEST['email'];
}
else
{
if(isset($_REQUEST['name']) && !empty($_REQUEST['name'])){$from_name = stripslashes($_REQUEST['name']);}
$headers = "From: {$name} <{$_REQUEST['email']}>";
}
mail($my_email,$subject,$message,$headers);
?>
<b>Thank you <?php if(isset($_REQUEST['name'])){print stripslashes($_REQUEST['name']);} ?></b>
<?php
//---------------------------------------------
}
else
{
?>
<script type="text/javascript">
function validate_mail()
{
var mail_name=document.mail_form.name.value;
var mail_email=document.mail_form.email.value;
var mail_contact=document.mail_form.contact.value;
var mail_message=document.mail_form.message.value;
var mail_subject=document.mail_form.subject.value;
var spaceRegxp = /\w+/;
var emailRegxp = /^[\w\-\.\+]+\#[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;
var contactRegxp = /^\d+$/;
if (spaceRegxp.test(mail_name) != true){
alert("PLEASE CHECK NAME");
document.mail_form.name.focus();
return false;}
if (emailRegxp.test(mail_email) != true){
alert("PLEASE CHECK EMAIL");
document.mail_form.email.focus();
return false;}
if (contactRegxp.test(mail_contact) != true){
alert("PLEASE CHECK CONTACT NUMBER");
document.mail_form.contact.focus();
return false;}
if (spaceRegxp.test(mail_subject) != true){
alert("PLEASE CHECK Subject");
document.mail_form.subject.focus();
return false;}
if (spaceRegxp.test(mail_message) != true){
alert("PLEASE CHECK MESSAGE");
document.mail_form.message.focus();
return false;}
else {
document.mail_form.action = 'index.php?t=contact&i=25';
document.mail_form.btn_submit.disabled=1;
document.mail_form.btn_submit.value = ' PLEASE WAIT ... ';
document.mail_form.submit();
}
}
</script>
<form name = "mail_form" method="post" enctype="multipart/form-data">
<div><label for="name"> Full Name: </label> <input name="name" type="text" size="50" /> </div>
<div><label for="address"> Address: </label> <input name="address" type="text" size="50" /></div>
<div><label for="email"> Email: </label><input name="email" type="text" size="50" /></div>
<div><label for="contact">Contact:</label> <input name="contact" type="text" size="50" /></div>
<div><label for="country">Country:</label> <input name="country" type="text" size="50" /> </div>
<div><label for="website">Website:</label> <input name="website" type="text" size="50" /> </div>
<div><label for="subject">Subject:</label> <input name="subject" type="text" size="50" /> </div>
<div><label for="message">Your Message:</label>
<textarea name="message" cols="40" rows="8"></textarea>
</div>
<div> <p> <input type="Button" name="btn_submit" id="submit-go" value=" Send Mail " onClick="validate_mail()"/> </p>
</div>
</form>
<?php
}
?>
Your code for sending mail through php has no issue at all.
if you are using WAMP in windows ,their will not have any SMTP server setup. so if you need to send mail from WAMP you need to use any SMTP server support.You can use Mandrill Mailchimb to send Email from localhost by just create an a/c in it, download swift files and add it in your working directory to setup mail server.To read-more on how to send mail through mandrill see below code..
or
You can work this code in a live server which supports SMTP setup.
Sending Mail via Mandrill Swift files in your code.You can change message subject etc as your own.
send_mail.php
<?php
if(isset($_POST['name']) != NULL && isset($_POST['email']) != NULL && isset($_POST['message']) != NULL ){
$name = strtoupper (trim($_POST['name']));
$address = trim($_POST['address']);
$email = strtolower(trim($_POST['email']));
$contact = trim($_POST['contact']);
$country = trim($_POST['country']);
$website = trim($_POST['website']);
$subject = trim($_POST['subject']);
$message = trim($_POST['message']);
//---------------------------------------------
error_reporting(E_ALL ^ E_NOTICE);
$my_email = "kiranpahadi#gmail.com";
$errors = array();
// Remove $_COOKIE elements from $_REQUEST.
if(count($_COOKIE)){foreach(array_keys($_COOKIE) as $value){unset($_REQUEST[$value]);}}
// Validate email field.
if(isset($_REQUEST['email']) && !empty($_REQUEST['email'])){
$_REQUEST['email'] = trim($_REQUEST['email']);
if(substr_count($_REQUEST['email'],"#") != 1 || stristr($_REQUEST['email']," ") || stristr($_REQUEST['email'],"\\") || stristr($_REQUEST['email'],":")){
$errors[] = "Email address is invalid";
}
else{
$exploded_email = explode("#",$_REQUEST['email']);
if(empty($exploded_email[0]) || strlen($exploded_email[0]) > 64 || empty($exploded_email[1])){
$errors[] = "Email address is invalid";
}
else{
if(substr_count($exploded_email[1],".") == 0){
$errors[] = "Email address is invalid";
}
else{
$exploded_domain = explode(".",$exploded_email[1]);
if(in_array("",$exploded_domain)){
$errors[] = "Email address is invalid";
}
else{
foreach($exploded_domain as $value){
if(strlen($value) > 63 || !preg_match('/^[a-z0-9-]+$/i',$value)){
$errors[] = "Email address is invalid";
break;
}
}
}
}
}
}
}
// Check referrer is from same site.
if(!(isset($_SERVER['HTTP_REFERER']) && !empty($_SERVER['HTTP_REFERER']) && stristr($_SERVER['HTTP_REFERER'],$_SERVER['HTTP_HOST']))){
$errors[] = "You must enable referrer logging to use the form";
}
// Check for a blank form.
function recursive_array_check_blank($element_value){
global $set;
if(!is_array($element_value)){
if(!empty($element_value)){
$set = 1;
}
}
else{
foreach($element_value as $value){
if($set){
break;
}
recursive_array_check_blank($value);
}
}
}
recursive_array_check_blank($_REQUEST);
if(!$set){
$errors[] = "You cannot send a blank form";
}
unset($set);
// Display any errors and exit if errors exist.
if(count($errors)){
foreach($errors as $value){
print "$value<br>";
}
exit;
}
if(!defined("PHP_EOL")){
define("PHP_EOL", strtoupper(substr(PHP_OS,0,3) == "WIN") ? "\r\n" : "\n");
}
// Build message.
function build_message($request_input){
if(!isset($message_output)){
$message_output ="";
}
if(!is_array($request_input)){
$message_output = $request_input;
}
else{
foreach($request_input as $key => $value){
if(!empty($value)){
if(!is_numeric($key)){
$message_output .= str_replace("_"," ",ucfirst($key)).": ".build_message($value).PHP_EOL.PHP_EOL;
}
else{
$message_output .= build_message($value).", ";
}
}
}
}
return rtrim($message_output,", ");
}
$message = build_message($_REQUEST);
$message = $message . PHP_EOL.PHP_EOL."-- ".PHP_EOL."The Message has been submitted successfully ";
$message = stripslashes($message);
$subject = stripslashes($subject);
if($email){
$headers = "From: {$name} <{$_REQUEST['email']}>";
$headers .= PHP_EOL;
$headers .= "Reply-To: " . $_REQUEST['email'];
}
else{
if(isset($_REQUEST['name']) && !empty($_REQUEST['name'])){
$from_name = stripslashes($_REQUEST['name']);
}
$headers = "From: {$name} <{$_REQUEST['email']}>";
}
include_once "swift/lib/swift_required.php";
$from = array("frommail#mail.com" => "Your Name");
$to="kiranpahadi#gmail.com";
$message = "Hello -This is a test mail";
$subject = "Subject – Test";
$transport = Swift_SmtpTransport::newInstance('smtp.mandrillapp.com', 587);
$transport->setUsername('kiranpahadi#gmail.com');
$transport->setPassword('eWTy3pUA1Okb-4lwUtk4dg');
$swift = Swift_Mailer::newInstance($transport);
sleep(2);
$html = "" . $message . "";
$maildetails = new Swift_Message($subject);
$maildetails->setFrom($from);
$maildetails->setBody($html, 'text/html');
$maildetails->setTo($to);
$maildetails->addPart($message, 'text/plain');
if ($recipients = $swift->send($maildetails, $failures)) {
echo 'Message successfully sent!';
} else {
echo "There was an error:n";
//print_r($failures);
}
//mail($my_email,$subject,$message,$headers);
?>
<b>Thank you <?php if(isset($_REQUEST['name'])){print stripslashes($_REQUEST['name']);} ?></b>
<?php
}
else{
?>
<form name = "mail_form" method="post" action ="send_mail.php"enctype="multipart/form-data">
<div><label for="name"> Full Name: </label> <input name="name" type="text" size="50" /> </div>
<div><label for="address"> Address: </label> <input name="address" type="text" size="50" /></div>
<div><label for="email"> Email: </label><input name="email" type="email" size="50" /></div>
<div><label for="contact">Contact:</label> <input name="contact" type="text" size="50" /></div>
<div><label for="country">Country:</label> <input name="country" type="text" size="50" /> </div>
<div><label for="website">Website:</label> <input name="website" type="text" size="50" /> </div>
<div><label for="subject">Subject:</label> <input name="subject" type="text" size="50" /> </div>
<div><label for="message">Your Message:</label>
<textarea name="message" cols="40" rows="8"></textarea>
</div>
<div><p><input type="submit" name="btn_submit" id="submit-go" value="Send Mail"/></p></div>
</form>
<?php
}
?>
# i just removed some of the unwanted lines from your code..
You can download swift files from http://ajesh.co.in/downloads/swift.zip
WAMP does not have an SMTP server.
Explanation
To be able to send email you need an outgoing email server. In most Linux systems there exists one by default, and PHP will use sendmail, a Linux app for submitting mail to whichever mail transfer agent you have installed.
In Windows, to be able to send mail from PHP you need an outgoing mail server somewhere and you need to tell PHP the address and port of it. This is done in php.ini using the SMTP and smtp_port settings. It will default to 'localhost' on port 25. Unless you have set up a mail server on that machine, that will fail.
If your ISP gives you an outgoing mail server, for example, you could use its address and port number. Or, if you're serious about sending mail, you'd set up your own mail server on the local machine or someone in your local network.
SOURCE Why mail() PHP function does not work with WAMP default installation?

Contact Form working in Chrome, not in IE/Firefox

Having some trouble with the contact form on my website, http://www.techcom.co.nz/
It works fine on google chrome, however on IE and Firefox it doesn't send any message and just redirects back up to the top of the page/refreshes the page.
Here is the php code for the form:
// EDIT THE FOLLOWING LINE BELOW AS REQUIRED
$send_email_to = "techcomnz#gmail.com";
function send_email($name,$email,$email_subject,$email_message)
{
global $send_email_to;
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
$headers .= "From: ".$email. "\r\n";
$message = "<strong>Email = </strong>".$email."<br>";
$message .= "<strong>Name = </strong>".$name."<br>";
$message .= "<strong>Message = </strong>".$email_message."<br>";
#mail($send_email_to, $email_subject, $message,$headers);
return true;
}
function validate($name,$email,$message,$subject)
{
$return_array = array();
$return_array['success'] = '1';
$return_array['name_msg'] = '';
$return_array['email_msg'] = '';
$return_array['message_msg'] = '';
$return_array['subject'] = '';
if($email == '')
{
$return_array['success'] = '0';
$return_array['email_msg'] = 'email is required';
}
else
{
$email_exp = '/^[A-Za-z0-9._%-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
if(!preg_match($email_exp,$email)) {
$return_array['success'] = '0';
$return_array['email_msg'] = 'enter valid email.';
}
}
if($name == '')
{
$return_array['success'] = '0';
$return_array['name_msg'] = 'name is required';
}
else
{
$string_exp = "/^[A-Za-z .'-]+$/";
if (!preg_match($string_exp, $name)) {
$return_array['success'] = '0';
$return_array['name_msg'] = 'enter valid name.';
}
}
if($subject == '')
{
$return_array['success'] = '0';
$return_array['subject_msg'] = 'subject is required';
}
if($message == '')
{
$return_array['success'] = '0';
$return_array['message_msg'] = 'message is required';
}
else
{
if (strlen($message) < 2) {
$return_array['success'] = '0';
$return_array['message_msg'] = 'enter valid message.';
}
}
return $return_array;
}
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$subject = $_POST['subject'];
$return_array = validate($name,$email,$message,$subject);
if($return_array['success'] == '1')
{
send_email($name,$email,$subject,$message);
}
header('Content-type: text/json');
echo json_encode($return_array);
die();
?>
and here is the html:
<fieldset id="contact_form">
<div id="msgs"> </div>
<form id="cform" name="cform" method="post" action="">
<input type="text" id="name" name="name" value="Full Name*" onfocus="if(this.value == 'Full Name*') this.value = ''"
onblur="if(this.value == '') this.value = 'Full Name*'" />
<input type="text" id="email" name="email" value="Email Address*" onfocus="if(this.value == 'Email Address*') this.value = ''"
onblur="if(this.value == '') this.value = 'Email Address*'" />
<input type="text" id="subject" name="subject" value="Subject*" onfocus="if(this.value == 'Subject*') this.value = ''"
onblur="if(this.value == '') this.value = 'Subject*'" />
<textarea id="msg" name="message" onfocus="if(this.value == 'Your Message*') this.value = ''"
onblur="if(this.value == '') this.value = 'Your Message*'">Your Message*</textarea>
<button id="submit" class="button" style=""> Send Message</button>
</form>
</fieldset>
Any help would be greatly appreciated.
Regards
Leaving the action attribute blank will cause most browsers to submit the form data to the current page by reloading it with the data in GET or POST.
If this is your intention, try removing the action="" altogether as it has been known to cause issues with older browsers.

PHP, trying to add captcha to existing form

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>

PHP Web Form Error Display

I am a PHP newb. I have the following code for a web form. It works fine as is, but I would like to do the following:
Return the errors as an array (?) so I can display errors as individual lines under each input.
and
Disallow the form from being able to be submitted twice.
Any help would be greatly appreciated.
<form id="form1" method="post" action="<?= $_SERVER['PHP_SELF'] ?>">
<fieldset>
<legend>Contact Me</legend>
<?php
if (isset($_POST['Submit'])) {
if ($_POST['firstname'] != "") {
$_POST['firstname'] = filter_var($_POST['firstname'], FILTER_SANITIZE_STRING);
if ($_POST['firstname'] == "") {
$errors .= 'Please enter a valid first name.<br/><br/>';
}
} else {
$errors .= 'Please enter your first name.<br/>';
}
if ($_POST['lastname'] != "") {
$_POST['lastname'] = filter_var($_POST['lastname'], FILTER_SANITIZE_STRING);
if ($_POST['lastname'] == "") {
$errors .= 'Please enter a valid last name.<br/><br/>';
}
} else {
$errors .= 'Please enter your last name.<br/>';
}
if ($_POST['email'] != "") {
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors .= "$email is <strong>NOT</strong> a valid email address.<br/><br/>";
}
} else {
$errors .= 'Please enter your email address.<br/>';
}
if ($_POST['message'] != "") {
$_POST['message'] = filter_var($_POST['message'], FILTER_SANITIZE_STRING);
if ($_POST['message'] == "") {
$errors .= 'Please enter a message to send.<br/>';
}
} else {
$errors .= 'Please enter a message to send.<br/>';
}
if (!$errors) {
$mail_to = '***#****.com';
$subject = 'New Mail from Web Site';
$message = 'From: ' . $_POST['firstname'] . " " . $_POST['lastname'] . "\n";
$message .= 'Email: ' . $_POST['email'] . "\n";
$message .= "Message:\n" . $_POST['message'] . "\n\n";
mail($mail_to, $subject, $message);
echo "<p>Thank you for your email!<br/><br/></p>";
} else {
echo '<div style="color: #00CC00">' . $errors . '<br/></div>';
}
}
?>
<label>First Name:</label>
<input type="text" name="firstname" value="<?php echo $_POST['firstname']; ?>" size="50" />
<label>Last Name:</label>
<input type="text" name="lastname" value="<?php echo $_POST['lastname']; ?>" size="50" />
<label>Email Address:</label>
<input type="text" name="email" value="<?php echo $_POST['email']; ?>" size="50"/>
<label>Message:</label>
<textarea name="message" rows="5" cols="50"><?php echo $_POST['message']; ?></textarea>
<br/>
<input type="submit" class="moveright" name="Submit" value="Submit" />
</fieldset>
</form>
You can use an array for the errors instead of concatenating them into one string. Then you can check for each error at the specified form input.
Sample error check
// instead of: $errors .= 'Please enter a message to send.<br/>';
if ($_POST['message'] == "")
$errors['message'] = 'Please enter a message to send.<br/>';
Sample error display
<label>Message:</label>
<?php if ($errors['message'] != "") echo $errors['message']; ?>
<textarea name="message" rows="5" cols="50"><?php echo $_POST['message']; ?></textarea>
Instead of appending each error to the string, do like the following:
$errors[] = 'error text';
EDIT: as the others have said, it's good practice to initialize the array before starting to set the values, like so: $errors = array();
As for the disallowing the form to be submitted twice, that needs javascript. Here's a link to help: http://www.webmasterworld.com/forum91/3781.htm
To make your errors into an array, initialize it before form processing as:
$errors = array();
if (isset($_POST['Submit'])) {
...
Each time you have an error, rather than concatenating it on with .=, use the [] array append syntax:
$errors[] = 'Please enter a message to send.';
To prevent the form from being submitted twice, we often use a variable in $_SESSION to indicate that it has been completed. On successful submission, set a $_SESSION['success'] flag. Don't forget also to initialize the session at the start of the script:
session_start();
$_SESSION['success'] = FALSE;
$errors = array();
// Only process the form if the session flag isn't set:
if (isset($_POST['Submit']) && !$_SESSION['success']) {
...
// Later, on success,
echo "<p>Thank you for your email!<br/><br/></p>";
// Set the flag to prevent resubmission.
$_SESSION['success'] = TRUE;

Categories