I have a pretty basic PHP site and I want a simple spam protection to stop the spam submissions.
I've found one that I like which is a basic 4 character input. Easy to read, small space requirements.
But it says to use a validate.php for the submission action.
My current form's action is to call a the mailer.php (<form id="contact-form" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" class="validate-form">) which is actually included on page load (<?php include 'includes/mailer.php'; ?>).
Can I have two 'actions'? If not, how can I implement the use of this captcha?
When I try adding session_start();
if(isset($_POST["captcha"])&&$_POST["captcha"]!=""&&$_SESSION["code"]==$_POST["captcha"])
{
echo "Correct Code Entered";
//Do you stuff
Just after the opening <?php in mailer.php and then }
else
{
die("Wrong Code Entered");
} just before the closing ?>, the whole website just displays "Wrong code entered" on load.
EDIT:
I'm having trouble understanding where I need to place the various parts of the code and how to tweak it so it works with the existing mailer script.
My unmodified index.php basically consists of the following:
<?php
include 'includes/mailer.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="css/bootstrap.css">
<link rel="stylesheet" href="css/bootstrap-responsive.css">
<link rel="stylesheet" href="css/styles.css">
</head>
<body>
<section id="section-home">
<header>
<!-- header content -->
<!-- navigation -->
</header>
</section>
<section class="banner full-width-container">
<div class="container">
<!-- other body content -->
<div id="contact">
<div id="contact-form-message"><?php print $output; ?></div>
<form id="contact-form" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" class="validate-form">
<p><span style="color:#f7403a;">Fill in the form below to have an expert contact you</span></p>
<div class="form-left">
<div class="control-group">
<label for="name" class="assistive control-label">Name:</label>
<div class="controls">
<input type="text" name="name" id="name" value="Your Name" class="replace-default required type-text" />
</div>
</div>
<div class="control-group">
<label for="email" class="assistive control-label">Email: </label>
<div class="controls">
<input type="text" name="email" id="email" value="Your email address" class="replace-default required type-text" />
</div>
</div>
</div><!-- end form-left -->
<div class="form-right">
<div class="control-group">
<label for="subject" class="assistive control-label">Subject: </label>
<div class="controls">
<input type="text" name="subject" id="subject" value="Subject" class="replace-default required type-text" />
</div>
</div>
<div class="control-group">
<label for="telephone" class="assistive control-label">Telephone number </label>
<div class="controls">
<input type="text" name="telephone" id="telephone" value="Your phone number" class="replace-default required type-text" />
</div>
</div>
</div><!-- end form-right -->
<div class="control-group">
<label for="message" class="assistive control-label">Message: </label>
<div class="controls">
<textarea name="message" id="message" class="replace-default required type-textarea full-width" rows="5" cols="20">The type of enquiry (e.g. Motor Accident) and a brief message</textarea>
</div>
</div>
<div class="control-group">
<div class="controls">
<input type="submit" id="submit" name="submit" class="btn btn-stacks" value="Send Message"/>
<div id="sending-message"><img src="img/ajax-loader.gif" alt="" /></div>
</div>
</div>
</form>
</div>
</div>
</section>
<footer class="full-width-container" id="footer-section">
<div class="container">
<!-- footer content -->
</div>
</footer>
<!-- ============================================== -->
<script src="js/modernizr-1.7.min.js"></script>
<script src="js/jquery-1.8.2.min.js"></script>
<script src="js/bootstrap.js"></script>
<script src="js/jquery.validate.min.js"></script>
<script src="js/jquery.flexslider-min.js"></script>
<script src="js/waypoints.min.js"></script>
<script src="js/jquery.scrollTo-1.4.3.1-min.js"></script>
<script src="js/custom.js"></script>
</body>
</html>
And my unmodified mailer.php consist of:
<?php
function cleanInput($input){
$input = trim($input);
if(strlen($input)>0){
$input = htmlspecialchars(stripslashes($input));
}
return $input;
}
$name = '';
$email = '';
$subject = '';
$message = '';
$telephone = '';
$output = '';
if ( isset($_POST['submit']) || isset($_GET['ajax']) == 'true'){
//set up for form fields
$name = cleanInput($_POST['name']);
$email = cleanInput($_POST['email']);
$subject = cleanInput($_POST['subject']);
$telephone = cleanInput($_POST['telephone']);
$message = cleanInput($_POST['message']);
$output ='';
$regex = "/^([a-z0-9\\+_\\-]+)(\\.[a-z0-9\\+_\\-]+)*#([a-z0-9\\-]+\\.)+[a-z]{2,6}$/ix";
//do some basic validation
if( $name == '' || $name == 'Full Name' ){ $output = '<li class="alert alert-error">Please enter your name.</li>'; }
if ( !preg_match( $regex, $email ) || $email == 'Email address' ) {
$output .= '<li class="alert alert-error">Please check that your email address is valid</li>';
}
if( $subject == '' || $subject == 'Subject' ){ $output .= '<li class="alert alert-error">Please enter a subject</li>'; }
if( $telephone == '' || $telephone == 'Contact number' ){ $output .= '<li class="alert alert-error">Please enter a contact number</li>'; }
if( $message == '' || $message == 'Your Query' ){ $output .= '<li class="alert alert-error">Please enter a message</li>'; }
//if there are errors, add them to the list here
if ( $output!='' ){
$output = '<div class=""><ul class="unstyled">' . $output . '</ul></div>';
}
//if no errors, try to send the form
else {
/*Put the email address to send to here*/
$to = "email1#domain.com.au";
$headers = 'From: noreply#domain.com.au' . "\r\n";
$headers .= 'Cc: '. $email . "\r\n";
$headers .= 'Bcc: email2#domain.com.au' . ', ' . 'email3#domain.com.au' . ', ' . 'email4#otherdomain.com.au' . "\r\n";
$subject = $subject;
$body = "Name: $name\n\n"
. "Email: $email\n\n"
. "Subject: $subject\n\n"
. "Message: $message"
;
$messageOK = ( mail($to, 'Web Enquiry from the landing page for: ' . $subject, $body, $headers ));
//check if the mail was sent or not
if ( $messageOK ){
$output = '<div class="alert alert-success"><p>Thank you for getting in touch. We will be in contact soon.</p></div>';
}
else {
$output = '<div class="alert alert-error"><p>We could not send your message. Please try again.</p></div>';
}
}
//if ajax is being used, output the message
if ( isset($_GET['ajax']) == 'true' ){
print $output;
}
}
?>
Any information that helps me understand what is required to use this captcha code would be greatly appreciated
You could use a random number generated when form is generated, then passing the value using POST AND $_SESSION, and then compare 2 to see if they match. This is for bot protection/spam.
Would you like an example?
EDIT, didn't fully read the question.
What you want to do is to decide whether the page is loaded as POST request, if is not, then display the form, if is, validate $_POST fields and/or send email.
session_start();
$error = null;
if(isset($_POST["captcha"])&&$_POST["captcha"]!=""&&$_SESSION["code"]==$_POST["captcha"])
{
echo "Correct Code Entered";
//Do you stuff`
else
{
$error = "invalid captcha image, please try again!";
}
//the rest of your HTML
//after the recaptcha image HTML
echo isset($error)? $error: '';
This will stop the page from dieing because of the failed captcha, and will produe an error message of 'Invalid captcha image' if the capthc was false.
Related
This question already has answers here:
PHP mail function doesn't complete sending of e-mail
(31 answers)
Closed 3 years ago.
I am trying to make a contact form for my website in php, but it seems something wrong somewhere, which i am unable to locate. Can you please help me to locate the error in the following code will be of great help and suggest further improvement on this.
Will of great help.
Thanks in advance.
<?php
// Message Vars
$msg = '';
$msgClass = '';
//check for submit
if (filter_has_var(INPUT_POST, 'submit')) {
//GET FORM DATA
$name = htmlspecialchars($_POST['name']);
$email = htmlspecialchars($_POST['email']);
$message = htmlspecialchars($_POST['message']);
// check required fields
if (!empty($email) && !empty($name) && !empty($message)) {
// passed
// check email
if (filter_var($email, FILTER_VALIDATE_EMAIL) == false) {
//failed
$msg = 'Please use a valid email';
$msgClass = 'alert-danger';
} else{
//passed
// reciepient email
$toEmail = 'myemail#gmail.com';
$subject = 'Contact Request From '.$name;
$body = '<h2> Contact Request</h2>
<h4> Name </h4><p>'.$name.'</p>
<h4> Email </h4><p>'.$email.'</p>
<h4> Message </h4><p>'.$message.'</p>';
// email headers
$headers = "MIME-Version: 1.0"."\r\n";
$headers .= "Content-Type: text/html;charset=UTF-8" . "\r\n";
// additional headers
$headers .= "From:" .$name. "<".$email.">". "\r\n";
if (mail($toEmail, $subject, $body, $headers)) {
// email sent
$msg = ' Your email has been sent';
$msgClass = 'alert-success';
}
}
# code...
} else {
//failed
$msg = ' Please fill in all fields';
$msgClass = 'alert-danger';
// failed
# code...
}
# code...
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Contact Us</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container" >
<?php if ($msg != ''): ?>
<div class="alert <?php echo $msgClass; ?> "><?php echo $msg; ?></div>
<?php endif; ?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<div class="contact-form" >
<h1>Contact Us</h1>
<div class="txtb" >
<label>Name</label>
<input type="text"
name="name"
class="form-control"
value="<?php echo isset($_POST['name']) ? $name : ''; ?>">
</div>
<div class="txtb" >
<label>Email</label>
<input type="text"
name="email"
class="form-control"
value="<?php echo isset($_POST['email']) ? $email : ''; ?>" >
</div>
<div class="txtb" >
<label>Message</label>
<textarea name="message" class="form-control" ><?php echo isset($_POST['message']) ? $message : ''; ?></textarea>
</div>
<br>
<a type="submit" name="submit" class="btn" >Submit</a>
</form>
</div>
</body>
</html>
I don't know what type of the error you're seeing but there's a little thing to change
You need to change
<a type="submit" name="submit" class="btn" >Submit</a>
to
<input type="submit">
I am having trouble with a contact form for my website. So there are two parts to this problem.
First I want to know how and why every time I enter the contact link of my page, it automatically sends an email, upon entering the page, and when clicking submit (I only want it to do this one) .
So example:
I go to mywebsite.com then I click on the 'Contact Us' link page. Upon taking me to the contact form, an e-mail is sent automatically. I am then allowed to fill out the form and send another e-mail. I want to know how to prevent that from happening and why it happens.
Second. I have seen lots of answered questions about this but none of the ones I have looked up on this website have worked for me so far.
When I click submit, to submit the form, it sends the email but then stays on the same page without clearing all fields or giving a confirmation message. I had also tried to redirect the page to say something like 'message has been sent successfully' or anything on the lines of that.
I am going to post my code below, but here are some notes on what I have tried before I do.
I tried to include a header to redirect after clicking submit. I am either doing that incorrectly or it just does not work.
I have tried the redirection with a java code, but since doing that it automatically sends an email then redirects to the page I stated without actually going to the contact form page.
My code is the php and html in one. I am going to separate the two after I finish it but I want to get it working first before I organize this section.
While looking at my code please do not judge. I am not a professional at this and I do understand that there are errors. I have tried to keep it with 0 errors but just have been adding code on top of code now to try and get this to work and may have added errors. I am open to suggestions in order to achieve the same effect while breaking down my code if possible. One error I do know I have is my form-inline statement. I am intentionally missing the quote at the end because with the quote, the search bar on my site gets messed up.
I have looked into jquery and ajax as well but I would prefer if someone give me a solution using the same format that I currently have the code in, unless the format is the problem I guess.
I changed my actual domain to mydomain.com for the example.
I do understand too that there may be a lot of irrelevant code but I am not sure if any line may be the problem so I tried to make clear what each section of code does for my page and included everything jsut in case one of those may be the problem.
<?php
$nameErr = $emailErr = $numberErr = $websiteErr = "";
$name = $email = $number = $comment = $subject = "";
$datetime = date('d/m/Y H:i:s');
$ipaddress = $_SERVER['REMOTE_ADDR'];
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"])) {
$subject = "";
} else {
$subject = test_input($_POST["subject"]);
}
if (empty($_POST["number"])) {
$number = "";
} else {
$number = test_input($_POST["number"]);
}
if (empty($_POST["comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["comment"]);
}
}
$email_message = "Form details below.\n\n";
function clean_string($string) {
$bad = array(
"content-type",
"bcc:",
"to:",
"cc:",
"href"
);
return str_replace($bad, "", $string);
}
$email_message .= "Full Name: " . clean_string($name) . "\n";
$email_message .= "E-mail: " . clean_string($email) . "\n";
$email_message .= "Subject: " . clean_string($subject) . "\n";
$email_message .= "ipaddress: " . clean_string($ipaddress) . "\n";
$email_message .= "date and time: " . clean_string($datetime) . "\n";
$email_message .= "Phone#: " . clean_string($number) . "\n";
$email_message .= "Message: " . clean_string($comment) . "\n";
$email_from = $name . '<' . $email_from . '>';
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'From:' . $email_from . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
/* Send the message using mail() function */
$myemail = "contact#mydomain.com";
mail($myemail, $subject, $email_message, $headers);
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
sec_session_start();
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>My Domain - Contact</title>
<meta name="keywords" content="" />
<meta name="description" content="" />
<link href="../css/style.css" rel="stylesheet" type="text/css" media="screen" />
</head>
<body>
<div id="logo">
<h1><img src="../tab/mydoaminlogo.jpg" alt="" width="780" height="104" /></h1>
</div>
<hr />
<!-- end #logo -->
<div id="header">
<div id="menu">
<ul>
<li>Home</li>
<li class="current_page_item">News</li>
<li>Locations</li>
<li>About</li>
<li>Contact</li>
<?php if (login_check($mysqli) == true) : ?>
<li>Store</li>
<?php else: ?>
<li>LogIn</li>
<?php endif; ?>
<?php if (login_check($mysqli) == true) : ?>
<li>Log Out</li>
<?php else: ?>
<li>Sign-up</li>
</ul>
<?php endif; ?>
</div>
<!-- end #menu -->
<div id="search">
<form method="get" action="" class="form-inline>
<fieldset>
<input type="text" name="s" id="search-text" size="15" />
<input type="submit" id="search-submit" value="Search" />
</fieldset>
</form>
</div>
<!-- end #search -->
</div>
<!-- end #header -->
<!-- end #header-wrapper -->
<div id="page">
<div id="content_wide">
<div class="post">
<div class="entrycontact">
<div class="container">
<form id="contact" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
<h3>Contact Us</h3>
<h4>Please fill out completely</h4>
<fieldset>
<input placeholder="Your name" type="text" name="name" value="<?php echo $name;?>" tabindex="1" required autofocus>
<span class="error"> <?php echo $nameErr;?></span>
</fieldset>
<fieldset>
<input placeholder="Your Email Address" type="email" name="email" value="<?php echo $email;?>"tabindex="2" required>
<span class="error"> <?php echo $emailErr;?></span>
</fieldset>
<fieldset>
<input placeholder="Subject" type="tel" name="subject" value="<?php echo $subject;?>"tabindex="2" required>
<span class="error"><?php echo $numberErr;?></span>
</fieldset>
<fieldset>
<input placeholder="Number" type="tel" name="number" value="<?php echo $number;?>"tabindex="3" required>
<span class="error"><?php echo $numberErr;?></span>
</fieldset>
<fieldset>
<textarea placeholder="Type your message here...." name ="comment" tabindex="5" required><?php echo $comment;?></textarea>
</fieldset>
<fieldset>
<button name="submit" type="submit" id="contact-submit" data-submit="...Sending">Submit</button>
</fieldset>
</form>
</div>
</div>
</div>
</div>
<!-- end #content -->
<!-- end #sidebar -->
<div style="clear: both;"></div>
</div>
<!-- end #page -->
<div id="footer"></div>
<!-- end #footer -->
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>
Google Captcha Form With Send Mail
</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="css/bootstrap-theme.min.css">
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
<form id="contactform" action="action.php" method="post" class="form" role="form">
<div class="form-group">
<div class="row">
<div class="col-lg-3">
<label>Name:</label>
</div>
<div class="col-lg-5">
<input class="form-control required" id="vname" name="vname" placeholder="Your Name" type="text" required />
</div>
</div>
</div>
<br>
<div class="form-group">
<div class="row">
<div class="col-lg-3">
<label>Email:</label>
</div>
<div class="col-lg-5">
<input class="form-control required" id="vemail" name="vemail" placeholder="Your Email" type="email" required />
</div>
</div>
</div>
<br>
<div class="form-group">
<div class="row">
<div class="col-lg-3">
<label>Information:</label>
</div>
<div class="col-lg-5">
<textarea type="text" name="msg" id="msg" rows="5" cols="50" class="form-control"></textarea>
</div>
</div>
</div>
<br>
<div class="form-group">
<div class="row">
<div class="col-lg-3">
<label>Verify Whether Human</label>
</div>
<div class="col-lg-5">
<div class="g-recaptcha" data-sitekey="PRIVATE" class="form-control">
</div>
</div>
</div>
</div>
<br>
<div class="form-group">
<input type="submit" class="btn btn-success form-send" value="Send">
</div>
</form>
<script src="js/jquery.min.js"></script>
<script src="js/recaptcha.js"></script>
<script src="js/bootstrap.min.js"></script>
</body>
</html>
and here is the following php
<?php
$captcha;
if (isset($_POST['g-recaptcha-response'])) { $captcha = $_POST['g-recaptcha-response']; }
// Check for correct reCAPTCHA
$response = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret='PRIVATE'&response=" . $captcha . '&remoteip=' . $_SERVER['REMOTE_ADDR']);
if (!$captcha || $response.success == false) {
echo "Your CAPTCHA response was wrong";
exit ;
} else {
// Check for Blank Fields..
if ($_POST["vname"] == "" || $_POST["vemail"] == "" || $_POST["msg"] == "") {
echo "Please fill all required fields";
} else {
// Check if the "Sender's Email" input field is filled out
$email = $_POST['vemail'];
// Sanitize E-mail Address
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
// Validate E-mail Address
$email = filter_var($email, FILTER_VALIDATE_EMAIL);
if (!$email) {
echo "Invalid Sender's Email";
} else {
$to = 'jinam#evoplus.in';
$subject = 'New Form Entry';
$message = "New message was submitted from <br /> " . "<strong>" . $_POST['vname'] . "</strong>" . "<br /><br />The message is:<br />" . "<strong>" . $_POST['msg'] . "</strong>";
$headers = "From:" . $_POST['vname'] . "<" . $email . ">";
$headers .= "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
// Sender's Email
// Message lines should not exceed 70 characters (PHP rule), so wrap it
$message = wordwrap($message, 70, "\r\n");
// Send Mail By PHP Mail Function
if (mail($to, $subject, $message, $headers)) {
echo "Your mail has been sent successfully!";
} else {
echo "Failed to send email, try again.";
exit ;
}
}
}
}
?>
Notice: Use of undefined constant success - assumed 'success' in
C:\xampp\htdocs\captchaform\action.php on line 6
i am getting this error help me with this i triend decoding with json no help so where am i wrong
$response is having JSON data and PHP you can not use . operator to fetch its keys.
- Convert to array
- access the keys
as your response is something like this
{ "success": true, "challenge_ts": "2017-02-09T12:18:22Z", "hostname": "localhost" }
Do something like this:
$response = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret='PRIVATE'&response=" . $captcha . '&remoteip=' . $_SERVER['REMOTE_ADDR']);
// Convert json to array
$response = ($response) ? json_decode($response, true) : [];
// If array not empty then perform your logic
if ($res) {
if (!$captcha || $response['success'] == false) {
echo "Your CAPTCHA response was wrong";
exit ;
} else {
// your code
.....
....
}
}
This will work.
use json_decode()
$response = json_decode($response);
and check like this
if (!$captcha || $response->success == false) {
To see more in deep : http://php.net/manual/en/function.json-decode.php
I have no real experience with PHP, and so have just pulled bits of code from various answers to help construct a simple PHP contact form. I have spent two days trying to work out why various variations aren't working. I've included my code:
HTML :
<section class="form-section" id="form-section">
<div class="row headline">
<h3>Free Quotation</h3> </div>
<div class="row">
<form action="mailer.php" method="post" name="htmlform" class="contact-form" target="_blank">
<div class="col span-1-of-2">
<div class="row inputs">
<label for="name">Name</label>
<input name="name" placeholder="Your name" required="" type="text"> </div>
<div class="row inputs">
<label for="email">Email</label>
<input name="email" placeholder="Your email" required="" value="" type="email" class="required email"> </div>
<div class="row inputs">
<label for="business_name">Business Name</label>
<input value="" name="business_name" placeholder="Your business name" required="" type="text" class=""> </div>
</div>
<div class="col span-1-of-2 message-box-container">
<label class="text-box-label" for="message">In a few words, what are you looking for?</label>
<textarea name="message" placeholder="Your message"></textarea>
</div>
<div class="row form-messages">
<?php
if($_GET['success'] == 1) {
echo "<div class="success">Thank You! We'll aim to follow up as soon as possible</div>";
}
if($_GET['success'] == -1) {
echo "<div class="error">Oops something went wrong, please try again</div>";
}
?> </div>
<div class="col span-2-of-3">
<div class="clear">
<input type="submit" value="Find Out More" name="subscribe" class="button"> </div>
</div>
</form>
</div>
</section>
This is my mailer.php form:
<?php
// Get the form fields, removes html tags and whitespace.
$name = strip_tags(trim($_POST["name"]));
$name = str_replace(array("\r","\n"),array(" "," "),$name);
$business_name = strip_tags(trim($_POST["business-name"]));
$business_name = str_replace(array("\r","\n"),array(" "," "),$business_name);
$email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
$message = trim($_POST["message"]);
// Check the data.
if (empty($name) empty($business_name) OR empty($message) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
header("Location: http://www.thegreenbuddha.co.uk/index.php?success=-1#form");
exit;
}
// Set the recipient email address. Update this to YOUR desired email address.
$recipient = "chussell#thegreenbuddha.co.uk";
// Set the email subject.
$subject = "New contact from $name";
// Build the email content.
$email_content = "Name: $name\n";
$email_content .= "Email: $email\n\n";
$email_content .= "Message:\n$message\n";
$email_content .= "Business Name: $business_name \n";
// Build the email headers.
$email_headers = "From: $name <$email>";
// Send the email.
mail($recipient, $subject, $email_content, $email_headers);
// Redirect to the index.html page with success code
header("Location: http://www.thegreenbuddha.co.uk/index.php?success=1#form");
?>
When I have this on live preview both success and error messages display with PHP code. I have the file saved as a index.php. And when I submit it opens up the fresh page which is blank.
When I've added the new index.php and mailer.php to my cpanel, my website no longer displays!
Any suggestions or improvements?
Many thanks!
The following
<?php
if($_GET['success'] == 1) {
echo "<div class="success">Thank You! We'll aim to follow up as soon as possible</div>";
}
if($_GET['success'] == -1) {
echo "<div class="error">Oops something went wrong, please try gain</div>";
}
?>
Into
<?php
if($_GET['success'] == 1) {
echo '<div class="success">Thank You! We\'ll aim to follow up as soon as possible</div>';
}
if($_GET['success'] == -1) {
echo '<div class="error">Oops something went wrong, please try gain</div>';
}
?>
The following
if (empty($name) empty($business_name) OR empty($message) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
header("Location: http://www.thegreenbuddha.co.uk/index.php?success=-1#form");
exit;
}
Into
if (empty($name) || empty($business_name) || empty($message) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
header("Location: http://www.thegreenbuddha.co.uk/index.php?success=-1#form");
exit;
}
Please change the following also:
$business_name = strip_tags(trim($_POST["business-name"]));
Into
$business_name = strip_tags(trim($_POST["business_name"]));
I want to display error messages below the fields in my contact form. But Im not able to do so. Here is my code:-
contact.html
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" media="screen" href="styles.css" >
<script type="text/javascript" src="my.js"></script>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function(){
$('#submit').click(function(){
$.post("send.php", $("#mycontactform").serialize(), function(response) {
$('#success').html(response);
//$('#success').hide('slow');
});
return false;
});
});
</script>
</head>
<body>
<form id="mycontactform" class="contact_form" action="" method="post" name="contact_form">
<ul>
<li>
<h2>Contact Us</h2>
<span class="required_notification">* Denotes Required Field</span>
</li>
<li>
<label for="name">Name:</label>
<input type="text" id="name" name="name" placeholder="John Doe" required />
<small class="errorText"><?php echo $error["name"]; ?></small>
</li>
<li>
<label for="email">Email:</label>
<input type="email" name="email" id="email" placeholder="john_doe#example.com" required />
<span class="form_hint">Proper format "name#something.com"</span>
<small class="errorText"><?php echo $error["email"]; ?></small>
</li>
<li>
<label for="message">Message:</label>
<textarea name="message" id="message" cols="40" rows="6" required ></textarea>
<small class="errorText"><?php echo $error["message"]; ?></small>
</li>
<li>
<input type="button" class="submit" style="width:70px; text-align:center; height:30px; margin-left:200px; cursor:pointer" value="SEND" id="submit" />
</li><div id="success" style="color:red;"></div>
</form>
</body>
</html>
send.php
<?php
// Here we get all the information from the fields sent over by the form.
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$to = 'babloopuneeth#gmail.com';
$subject = 'the subject';
$message = 'FROM: '.$name.' Email: '.$email.'Message: '.$message;
$headers = 'From: youremail#domain.com' . "\r\n";
$error = array(
"name" => "",
"email" => "",
"message" => ""
);
$email = ( isset( $_POST["email"] ) ) ? trim( $_POST["email"] ) : false;
$name = ( isset( $_POST["name"] ) ) ? trim( $_POST["name"] ) : false;
$message = ( isset( $_POST["message"] ) ) ? trim( $_POST["message"] ) : false;
if ( !$emai ) {
$error["email"] = "Email is required!";
}
if ( !$name ) {
$error["name"] = "Name is required!";
}
if ( !$message ) {
$error["message"] = "Message is required!";
}
else { // this line checks that we have a valid email address
mail($to, $subject, $message, $headers); //This method sends the mail.
echo "Your email was sent!"; // success message
}
?>
I tried many other ways but its not working. I just want the error message to be displayed below each field if the field is empty, Plz help me..
Use <br> after each input
$.post : http://api.jquery.com/jQuery.post/
it's jquery AJAX. so you can't display return message with <?php echo $error["name"]; ?> on your form page. You have to use javascript for displaying error messages.
You should use jQuery AJAX in order to retrieve server-side validation. Here is the material.
Just for information, it's better to use jQuery Validation to validate form. Check here for light and thorough examples. You could adapt the code to your case.