I've been busy this morning creating a custom WordPress contact page template and have added the new Google reCaptcha to it in an effort to reduce spammers. I have created a validation.php file which the contact page actions to validate that all fields and the Google reCaptcha are correct. The problem is it just isn't working for me. I have everything setup as it should be in the WordPress file system and WordPress is navigating to the validation.php file no problem which leads me to believe that my validation code isn't working. Please see below:
HTML CODE:
<div class="col-xs-12 col-sm-8 col-lg-9">
<script src='https://www.google.com/recaptcha/api.js'></script>
<div id="content" role="main">
<?php get_template_part('includes/loops/content', 'page'); ?>
<hr/>
<form action="validate-contact-form.php" id="contactForm" method="post">
<fieldset>
<legend>Contact Us</legend>
<div class="form-group">
<div class="col-md-12">
<input id="cf-name" name="contactName" type="text" placeholder="Please enter your full name here." class="form-control" required=""/>
</div>
</div>
<br /><br />
<div class="form-group">
<div class="col-md-12">
<input id="cf-email" name="email" type="text" placeholder="Please enter your e-mail address here." class="form-control" required="" />
</div>
</div>
<br /><br />
<div class="form-group">
<div class="col-xs-12">
<textarea class="form-control" id="comments" placeholder="Please enter your message here." name="comments" rows="20" class="form-control" required="" ></textarea>
</div>
</div><hr/>
<div class="form-group">
<div class="col-xs-12"><hr/>
<div class="g-recaptcha" data-sitekey="6Ld6cf4SAAAAABBYX2C3I5Ayx_xLwKSYm2ZUtxen" class="form-control" required=""></div>
</div>
</div>
<div class="form-group">
<div class="col-xs-12"><hr/>
<button type="submit" name="submit" value="Send" class="btn btn-primary">Send Message</button>
</div>
</div>
</fieldset>
</form>
</div><!-- /#content -->
</div>
Validation.php CODE:
<?php
if(isset($_POST['submit'])) {
if(trim($_POST['contactName']) === '') {
$nameError = 'Please enter your name.';
$hasError = true;
} else {
$name = trim($_POST['contactName']);
}
if(trim($_POST['email']) === '') {
$emailError = 'Please enter your email address.';
$hasError = true;
} else if (!preg_match("/^[[:alnum:]][a-z0-9_.-]*#[a-z0-9.-]+\.[a-z]{2,4}$/i", trim($_POST['email']))) {
$emailError = 'You entered an invalid email address.';
$hasError = true;
} else {
$email = trim($_POST['email']);
}
if(trim($_POST['comments']) === '') {
$commentError = 'Please enter a message.';
$hasError = true;
} else {
if(function_exists('stripslashes')) {
$comments = stripslashes(trim($_POST['comments']));
} else {
$comments = trim($_POST['comments']);
}
}
if(isset($_POST['g-recaptcha-response'])&&$_POST['g-recaptcha-response']){
var_dump($_POST);
$secret = 'MY SITE KEY';
$ip = $_SERVER['REMOTE_ADDR'];
$captcha = $_POST['g-recaptcha-response'];
$rsp = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret=$secret&response=$captcha&remoteip=$ip');
var_dump($rsp);
$array = json_decode($rsp, TRUE);
if($array['success']) {
}
}
if(!isset($hasError)) {
$emailTo = get_option('tz_email');
if (!isset($emailTo) || ($emailTo == '') ){
$emailTo = get_option('admin_email');
}
$subject = '[PHP Snippets] From '.$name;
$body = "Name: $name \n\nEmail: $email \n\nComments: $comments";
$headers = 'From: '.$name.' <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;
wp_mail($emailTo, $subject, $body, $headers);
$emailSent = true;
echo "Done";
}
else {
echo "Spam";
}
}
}
?>
Use double quotes:
$rsp = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=$secret&response=$captcha&remoteip=$ip");
Else the variables won't work. PHP will only search a string for variables and display their values if it's surrounded by double quotes. You can use single quotes, but then you have to seperate the variables and strings like this:
$rsp = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secret.'&response='.$captcha.'&remoteip='.$ip);
Performance wise, it's always better to use single quotes so PHP doesn't need to search a full string for variables.
Related
Currently on my site JorgeGoris.com I have a form that is pointing to a php file called form_process.php for validation. My problem is that I never see the validation or success messages I have implemented take place because when I hit submit I am redirected to form_process.php I want this to take place dynamically in the same page. How can I do this? This is my form and php code:
<?php
// define variables and set to empty values
$firstName_error = $email_error = $phone_error = "";
$firstName = $lastName = $email = $phone = $message = $success = "";
//form is submitted with POST method
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["firstname"])) {
$firstName_error = "First name is required";
} else {
$firstName = test_input($_POST["firstname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$firstName)) {
$firstName_error = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$email_error = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$email_error = "Invalid email format";
}
}
if (empty($_POST["phone"])) {
$phone_error = "Phone is required";
} else {
$phone = test_input($_POST["phone"]);
// check if e-mail address is well-formed
if (!preg_match("/^(\d[\s-]?)?[\(\[\s-]{0,2}?\d{3}[\)\]\s-]{0,2}?\d{3}[\s-]?\d{4}$/i",$phone)) {
$phone_error = "Invalid phone number";
}
}
if (empty($_POST["message"])) {
$message = "";
} else {
$message = test_input($_POST["message"]);
}
if ($firstName_error == '' and $email_error == '' and $phone_error == '' ){
$message_body = '';
unset($_POST['submit']);
foreach ($_POST as $key => $value){
$message_body .= "$key: $value\n";
}
$to = 'J_goris#live.com';
$subject = 'Potential Client/Employer-JorgeGoris';
if (mail($to, $subject, $message_body)){
$success = "Message sent, I'll get back to you shortly!";
$firstName = $email = $phone = $message = '';
echo "<h1>Got it! I'll get back to you shortly!</h1>";
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<form action="form_process.php" method="post" name="contact_form">
<div class="form-row">
<div class="col-lg-3 offset-lg-3 col-sm-12">
<input type="text" class="form-control" placeholder="First Name *" name="firstname">
<span class="error"><?php= $firstName_error ?></span>
</div><!--end col-->
<div class="col-lg-3 col-sm-12">
<input type="text" class="form-control" placeholder="Last Name" name="lastname">
</div><!--end col-->
</div><!--end row-->
<div class="form-row">
<div class="col-lg-3 offset-lg-3 col-sm-12">
<input type="text" class="form-control" placeholder="Phone Number" name="phone">
<span class="error"><?php= $phone_error ?></span>
</div><!--end col-->
<div class="col-lg-3 col-sm-12">
<input type="email" class="form-control" placeholder="Email *" name="email">
<span class="error"><?php= $email_error ?></span>
</div><!--end col-->
</div><!--end row-->
<div class="row">
<div class="col-lg-5 offset-lg-3 col-sm-12">
<textarea class="form-control" rows="5" placeholder="Tell me a little about your project. Budget details are also appreciated. *" name="message"></textarea>
</div><!--end col-->
</div><!--end row-->
<div class="success"><?php= $success; ?></div>
<button type="submit" class="button" name="submit">Submit</button>
</form><!--end form-->
The proper method to achieve the desired functionality is to have your form-data sent to the PHP file (or function) which is responsible for loading the form. The PHP code which loads the form should be conditional. For example you can have a check for errors in the submitted post-data and if there's an error some HTML code that displays the error should be outputted in addition to the normal HTML code of the form.
In your case you don't see anything when you hit the submit button because the PHP script to which your form is pointing doesn't output the HTML of the page that contains the form.
In the process of setting up a website for myself, i've hit a bit of a road block with the PHP contact form. I believe it is coded correctly, but whenever I upload it to my site and try to use the contact form I get "Page is forbidden 403". I'm using Hostinger by the way, i've set the permissions of my public_html file to 755. Not sure what the problem could be. Included is my code, any help would be greatly appreciated.
Contact code of the HTML from the index:
<div class="row stay-behind" id="contact">
<h4 class="right-name">Contact</h4>
<div class="col-md-1"></div>
<div class="col-sm-12 col-md-4 feature-image"><img alt="VX1K" height="510" src="images/ux/004.jpg" width="374"> <img alt="VX1K" class="mobile-only" src="images/ux/mobile/004.jpg"></div>
<div class="col-sm-12 col-md-6 main">
<h3 class="title">Contact</h3>
<form class="contact-form" id="contactForm" novalidate method="post" action="public_html/mail/contact_me.php">
<div id="form-alert"></div>
<div class="form-group">
<input class="form-control" id="name" name="name" placeholder="Name" type="name">
</div>
<div class="form-group">
<input class="form-control" id="email" name="email" placeholder="Email" type="email">
</div>
<textarea class="form-control" id="message" placeholder="Message" rows="3"></textarea> <input class="btn btn-block btn-primary" id="btnSubmit" name="submit" type="submit" value="Send">
</form>
</div>
<div class="col-md-1"></div>
Code from the PHP file.
<?php
function Validate()
{
// Check for empty fields
if (empty($_POST['name']) || empty($_POST['email']) || empty($_POST['message']) || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL))
{
return false;
}
else return true;
}
function SendEmail($to = 'noreply#vx1k.com')
{
if (Validate() == true)
{
$name = $_POST['name'];
$email_address = $_POST['email'];
$message = $_POST['message'];
// Create the email and send the message
$email_subject = "Website Contact Form: $name";
$email_body = "You have received a new message from your website contact form.\n\n" . "Here are the
details:\n\nName: $name\n\nEmail: $email_address\n\nMessage:\n$message";
$headers = "From: noreply#vx1k.com\n";
$headers.= "Reply-To: $email_address";
// Send true on successful send.
// Send false if failed
return (mail($to, $email_subject, $email_body, $headers)) ? true : false;
}
else
// Invalid inputs
return 'err';
}
// Apply function(s). You will get true, false, or err
$send = SendEmail();
// On return, you can echo any result
if ($send == 'err') echo 'Invalid Fields.';
elseif ($send == false) echo 'An Error Occurred.';
else echo 'Email Sent Successfully.';
?>
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"]));
So im really bad when it comes to php forms, im getting the message "Sorry,
Your message can't be send...check if your email is correct otherwise a field is missing..."
other people are using the site saying it is bouncing back also.
HOW IT LOOKS
PHP
The folder isnt in a php foler it is out with the html pages.
<?php
//set your email here:
$yourEmail = 'emma#peacehavengc.com';
/*
* CONTACT FORM
*/
//If the form is submitted
if(isset($_POST['submitted'])) {
//Check to make sure that the name field is not empty
if($_POST['contact_name'] === '') {
$hasError = true;
} else {
$name = $_POST['contact_name'];
}
//Check to make sure sure that a valid email address is submitted
if($_POST['emma#peacehavengc.com'] === '') {
$hasError = true;
} else if (!preg_match("/^[a-z0-9]+([_\\.-][a-z0-9]+)*#([a-z0-9]+([\.-][a-z0-9]+)*)+\\.[a-z]{2,}$/i", $_POST['emma#peacehavengc.com'])) {
$hasError = true;
} else {
$email = $_POST['emma#peacehavengc.com'];
}
//Check to make sure comments were entered
if($_POST['contact_textarea'] === '') {
$hasError = true;
} else {
if(function_exists('stripslashes')) {
$comments = stripslashes($_POST['contact_textarea']);
} else {
$comments = $_POST['contact_textarea'];
}
}
//If there is no error, send the email
if(!isset($hasError)) {
$emailTo = $yourEmail;
$subject = "Message From Your Website";
$body = "Name: $name \n\nEmail: $email \n\nComments: $comments";
$headers = 'From : my site <'.$emailTo.'>' . "\r\n" . 'answer to : ' . $email;
mail($emailTo, $subject, $body, $headers);
$emailSent = true;
}
}
?>
HTML
<div class="center">
<h3>Get in touch Now</h3>
</div>
<form class="form-horizontal" method="post" action="contact.php" id="form">
<div class="form-group">
<label for="contact_name" class="col-lg-2 control-label">Name</label>
<div class="col-lg-10">
<input type="text" class="form-control" id="contact_name" name="contact_name">
</div>
</div>
<div class="form-group">
<label for="contact_email" class="col-lg-2 control-label">Email</label>
<div class="col-lg-10">
<input type="email" class="form-control" id="contact_email" name="contact_email">
</div>
</div>
<div class="form-group">
<label for="contact_textarea" class="col-lg-2 control-label">Message</label>
<div class="col-lg-10">
<textarea class="form-control" rows="3" id="contact_textarea" name="contact_textarea"></textarea>
</div>
</div>
<div class="form-group">
<div class="col-lg-offset-2 col-lg-10">
<input type="hidden" name="submitted" id="submitted" value="true" />
<button type="submit" class="btn btn-default" name="submitted"><i class="icon-paperplane"></i>Send</button>
</div>
</div>
</form>
Check This.
<?php
$yourEmail = 'emma#peacehavengc.com';
if(isset($_POST['submitted']))
{
if($_POST['contact_name'] == '')
{
$hasError = true;
}
else
{
$name = $_POST['contact_name'];
}
//Check to make sure sure that a valid email address is submitted
if($_POST['contact_email'] == '')
{
$hasError = true;
}
else if (!preg_match("/^[a-z0-9]+([_\\.-][a-z0-9]+)*#([a-z0-9]+([\.-][a-z0-9]+)*)+\\.[a-z]{2,}$/i", $_POST['contact_email']))
{
$hasError = true;
}
else
{
$email = $_POST['contact_email'];
}
//Check to make sure comments were entered
if($_POST['contact_textarea'] == '')
{
$hasError = true;
}
else
{
if(function_exists('stripslashes'))
{
$comments = stripslashes($_POST['contact_textarea']);
}
else
{
$comments = $_POST['contact_textarea'];
}
}
//If there is no error, send the email
if(!isset($hasError))
{
$emailTo = $yourEmail;
$subject = "Message From Your Website";
$body = "Name: $name \n\nEmail: $email \n\nComments: $comments";
$headers = "From: my site <$emailTo>" . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html;\n\tcharset=\"iso-8859-1\"\r\n";
mail($emailTo, $subject, $body, $headers);
$emailSent = true;
}
header("location:contact.html");
}
?>
I am creating a site on Yahoo Small Business hosting, and am having issues with the PHP contact form that I use on my WordPress install on Bluehost. The form is:
<?php
if(isset($_POST['submitted'])) {
if(trim($_POST['contactName']) === '') {
$nameError = 'Please enter your name.';
$hasError = true;
} else {
$name = trim($_POST['contactName']);
}
if(trim($_POST['email']) === '') {
$emailError = 'Please enter your email address.';
$hasError = true;
} else if (!preg_match("/^[[:alnum:]][a-z0-9_.-]*#[a-z0-9.-]+\.[a-z]{2,4}$/i", trim($_POST['email']))) {
$emailError = 'You entered an invalid email address.';
$hasError = true;
} else {
$email = trim($_POST['email']);
}
if(!isset($hasError)) {
$emailTo = get_option('tz_email');
if (!isset($emailTo) || ($emailTo == '') ){
$emailTo = 'chris#bingetech.com';
}
$subject = '[PHP Snippets] From '.$name;
$body = "Name: $name \n\nEmail: $email \n\nComments: $comments";
$headers = 'From: '.$name.' <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;
wp_mail($emailTo, $subject, $body, $headers);
$emailSent = true;
}
} ?>
<div id="contact-wrap">
<?php if(isset($emailSent) && $emailSent == true)
{ ?>
<div class="thanks">
<p>Thanks, your email was sent successfully.</p>
</div>
<?php } else { ?>
<?php the_content(); ?>
<?php if(isset($hasError) || isset($captchaError)) { ?>
<p class="error">Sorry, an error occurred.<p>
<?php } } ?>
<form action="<?php the_permalink(); ?>" id="contactForm" method="post">
<ul class="formList">
<li>
<label class="contact_labels" for="contactName">Name:</label>
<input type="text" name="contactName" id="contactName" value="<?php if(isset($_POST['contactName'])) echo $_POST['contactName'];?>" class="required requiredField" />
<?php if($nameError != '') { ?>
<span class="error"><?=$nameError;?></span>
<?php } ?>
</li>
<li>
<label class="contact_labels" for="email">Email: </label>
<input type="email" name="email" id="email" value="<?php if(isset($_POST['email'])) echo $_POST['email'];?>" class="required requiredField email" />
<?php if($emailError != '') { ?>
<span class="error"><?=$emailError;?></span>
<?php } ?>
</li>
</ul>
<div id="subContain">
<input type="submit" id="submit" value="Ask Away!"></input>
</div>
<input type="hidden" name="submitted" id="submitted" value="true" />
</form>
</div>
I have the appropriate header calls and this does work on Bluehost, and from my research it appears Yahoo Small Business hosting can be tricky with contact forms/email. How can I get around this?
You should use some plugin instead of your own PHP code. Try Contact form 7 its completely customize-able