PHP sending form doesn't work correctly - php

I'm testing a PHP form to send email in local.
I put all input but when I press the submit button it always returns "false" and then the error message. Is that because I'm working in local and don't have any mail server, or is there something wrong in my code?
here the code:
<?php
if(isset($_POST['submit']))
{
if(empty($_POST['nome']) ||
empty($_POST['email']) ||
empty($_POST['motivo']) ||
empty($_POST['messaggio']) ||
!filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
{
echo "No arguments Provided!";
// return false;
}
else
{
$nome = strip_tags(htmlspecialchars($_POST['nome']));
$email_address = strip_tags(htmlspecialchars($_POST['email']));
$motivo = strip_tags(htmlspecialchars($_POST['motivo']));
$messaggio = strip_tags(htmlspecialchars($_POST['messaggio']));
// Create the email and send the message
$to = 'mirkocoppola80#gmail.com'; // Add your email address inbetween the '' replacing yourname#yourdomain.com - This is where the form will send a message to.
$email_subject = "Website Contact Form: $nome";
$email_body = "You have received a new message from your website contact form.\n\n"."Here are the details:\n\nName: $nome\n\nEmail: $email_address\n\nOggetto: $motivo\n\nMessaggio:\n$messaggio";
$headers = "From: mirkocoppola80#gmail.com\n"; // This is the email address the generated message will be from. We recommend using something like noreply#yourdomain.com.
$headers .= "Reply-To: $email_address";
if (!#mail($to,$email_subject,$email_body,$headers))
{
// return true;
echo "<p>Email error</p>";
}
else
{
echo "<p>Email sent successfully!</p>";
}
}
}
?>
<form class="form-horizontal col-sm-6 col-sm-offset-3" action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="POST">
<div class="form-group">
<div class="row">
<label for="email" class="col-sm-12">Email</label>
</div>
<div class="row">
<div class="col-sm-12">
<input type="email" name="email" class="form-control" id="email" placeholder="Email">
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<label for="nome" class="col-sm-12">Nome</label>
</div>
<div class="row">
<div class="col-sm-12">
<input type="text" name="nome" class="form-control" id="nome" placeholder="Nome">
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<label for="motivo" class="col-sm-12">Motivo</label>
</div>
<div class="row">
<div class="col-sm-12">
<input type="text" name="motivo" class="form-control" id="motivo" placeholder="Motivo">
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<label for="messaggio" class="col-sm-12">Messaggio</label>
</div>
<div class="row">
<div class="col-sm-12">
<textarea class="form-control" name="messaggio" rows="5" id="messaggio" placeholder="Motivo">Inserisci il tuo messaggio...</textarea>
</div>
</div>
</div>
<div class="form-group">
<div class="">
<button type="submit" name="submit" class="btn btn-default">Invia</button>
</div>
</div>
</form>
Any help?

Is that because I'm working in local and don't have any mail server
Yes.
PHP's mail() function will always fail and return false if you don't have a local mail server running.
This answer has some useful tips
You need to setup a mail server on your machine for the mail function to work. If you are on Windows (which I am guessing you are from your use of WAMP) you can setup a Pegasus mail server.
Other options include using a wrapper class such as SwiftMailer or PHPMailer and using them to connect to another SMTP server such as your GMail account. Even if you go the Pegasus mail server on your own localhost route then I would still recommend using one of the two classes I have mentioned above. They give you far more flexibility and are safer.
Connecting to either your ISPs SMTP server or GMail or whatever is the easiest route out of this one.
To expand on the above, you can also look into Mailhog or Mailcatcher to capture your mail locally and examine its contents.

remove the "#" in
if (#mail($to,$email_subject,$email_body,$headers))
<?php
if(isset($_POST['submit']))
{
if(empty($_POST['nome']) ||
empty($_POST['email']) ||
empty($_POST['motivo']) ||
empty($_POST['messaggio']) ||
!filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
{
echo "No arguments Provided!";
// return false;
}
else
{
$nome = strip_tags(htmlspecialchars($_POST['nome']));
$email_address = strip_tags(htmlspecialchars($_POST['email']));
$motivo = strip_tags(htmlspecialchars($_POST['motivo']));
$messaggio = strip_tags(htmlspecialchars($_POST['messaggio']));
// Create the email and send the message
$to = 'mirkocoppola80#gmail.com'; // Add your email address inbetween the '' replacing yourname#yourdomain.com - This is where the form will send a message to.
$email_subject = "Website Contact Form: $nome";
$email_body = "You have received a new message from your website contact form.\n\n"."Here are the details:\n\nName: $nome\n\nEmail: $email_address\n\nOggetto: $motivo\n\nMessaggio:\n$messaggio";
$headers = "From: mirkocoppola80#gmail.com\n"; // This is the email address the generated message will be from. We recommend using something like noreply#yourdomain.com.
$headers .= "Reply-To: $email_address";
if (mail($to,$email_subject,$email_body,$headers))
{
// return true;
echo "<p>Email error</p>";
}
else
{
echo "<p>Email sent successfully!</p>";
}
}
}
?>
it should work then.

Related

Receiving 500 Server Error with Contact Form Submission.php

I've looked through a bunch of similar issues but haven't been able to find an answer that works. I recently switched my website over to a different host and am trying to set up the contact form. I am getting a 500 error when I click submit. I've made sure the SMTP is set up correctly. I just don't know what else to try at this point. Here's my code:
HTML:
<form role="form" method="POST" action="contact-form-submission.php">
<div class="row">
<div class="form-group col-lg-4">
<label for="input1">Name</label>
<input type="text" name="contact_name" class="form-control" id="input1">
</div>
<div class="form-group col-lg-4">
<label for="input2">Email Address</label>
<input type="email" name="contact_email" class="form-control" id="input2">
</div>
<div class="form-group col-lg-4">
<label for="input3">Phone Number</label>
<input type="phone" name="contact_phone" class="form-control" id="input3">
</div>
<div class="clearfix"></div>
<div class="form-group col-lg-12">
<label for="input4">Message</label>
<textarea name="contact_message" class="form-control" rows="6" id="input4"></textarea>
</div>
<div class="form-group col-lg-12">
<input type="hidden" name="save" value="contact">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</form>
PHP:
<?php
// check for form submission - if it doesn't exist then send back to contact form
if (!isset($_POST['save']) || $_POST['save'] != 'contact') {
header('Location: contact.php'); exit;
}
// get the posted data
$name = $_POST['contact_name'];
$email_address = $_POST['contact_email'];
$phone = $_POST['contact_phone'];
$message = $_POST['contact_message'];
// check that a name was entered
if (empty($name))
$error = 'You must enter your name.';
// check that an email address was entered
elseif (empty($email_address))
$error = 'You must enter your email address.';
// check for a valid email address
elseif (!preg_match('/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/', $email_address))
$error = 'You must enter a valid email address.';
// check that a phone number was entered
if (empty($phone))
$error = 'You must enter your phone number.';
// check that a message was entered
elseif (empty($message))
$error = 'You must enter a message.';
// check if an error was found - if there was, send the user back to the form
if (isset($error)) {
header('Location: contact.php?e='.urlencode($error)); exit;
}
$headers = "From: $email_address\r\n";
$headers .= "Reply-To: $email_address\r\n";
// write the email content
$email_content = "Name: $name\n";
$email_content .= "Email Address: $email_address\n";
$email_content .= "Phone Number: $phone\n";
$email_content .= "Message:\n\n$message";
// send the email
//ENTER YOUR INFORMATION BELOW FOR THE FORM TO WORK!
mail ('EMAIL', 'Young & Company - Contact Form Submission', $email_content, $headers);
// send the user back to the form
header('Location: index.html'/*.urlencode('Thank you for your message.'*/)); exit;
?>
You need to look into PHP error log. Try this to show errors.
ini_set('display_errors', '1');
Post your logs here if you can't discern which logs are relevant. Most likely SMTP settings are be blamed. mail function opens a socket connection. using SMTP settings.
SMTP settings can be managed through ini or by:
ini_set('SMTP', 'smtphost');
ini_set('smtp_port', 25);
The above settings are just, for example, you need to have your own SMTP settings. For example, if you have a Gmail account, you may use it to send mail. It depends on your specific situation on which SMTP server you may want to use.
Here are the Gmail SMTP settings. Also, look at the documentation.
There is an error on the last line of contact-form-submission.php file.
You forget to remove the extra bracket from the below line.
Old
// send the user back to the form
header('Location: index.html'/*.urlencode('Thank you for your message.'*/)); exit;
New
// send the user back to the form
header('Location: index.html'/*.urlencode('Thank you for your message.'*/); exit;
Or include that bracket in comment tag.
// send the user back to the form
header('Location: index.html'/*.urlencode('Thank you for your message.')*/); exit;

Wordpress custom form, loads wrong template after submit, doesn't send mail

Im trying to build a simple contact form for a Wordpress site. I want it to send an email and reload the contact page it was sent from with an error/success message.
I have installed WP mail SMTP and it sends the test email.
Now to the problems. I have a form in html that I want to use. This form has been put in a custom template.
The php is borrowed from guides I have found online and I have used several of them. None of them work for me. When I hit the submit button the page loads the base template (not the custom template that I'm using for the form page) and no mail is sent. I want it to load the same page but with an error/success div telling me what happened. If I run the php before pressing submit it gives me the error message.
Here is my php:
if(isset($_POST['submitButton'])){
//response generation function
$response = "";
//function to generate response
function my_contact_form_generate_response($type, $reason){
global $response;
if($type == "success") $response = "<div class='success'>{$reason}</div>";
else $response = "<div class='error'>{$reason}</div>";
}
//response messages
$not_human = "Human verification incorrect.";
$missing_content = "Please supply all information.";
$email_invalid = "Email Address Invalid.";
$message_unsent = "Message was not sent. Try Again.";
$message_sent = "Thanks! Your message has been sent.";
//user posted variables
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$phone = $_POST['phone'];
$human = 2;
//php mailer variables
$to = get_option('admin_email');
$subject = "Someone sent a message from ".get_bloginfo('name');
$headers = 'From: '. $email . "\r\n" .
'Reply-To: ' . $email . "\r\n";
if(!$human == 0){
if($human != 2) my_contact_form_generate_response("error", $not_human); //not human!
else {
//validate email
if(!filter_var($email, FILTER_VALIDATE_EMAIL))
my_contact_form_generate_response("error", $email_invalid);
else //email is valid
{
//validate presence of name and message
if(empty($name) || empty($message)){
my_contact_form_generate_response("error", $missing_content);
}
else //ready to go!
{
$sent = mail($to, $subject, strip_tags($message),
$headers);
if($sent) my_contact_form_generate_response("success",
$message_sent); //message sent!
else my_contact_form_generate_response("error",
$message_unsent); //message wasn't sent
}
}
}
}
else if ($_POST['submitted'])
my_contact_form_generate_response("error", $missing_content);
}
?>
Here is my html for the "print error/success" and the form:
<?php echo $response; ?>
<form class="interest-form" action="<?php the_permalink(); ?>" method="POST">
<fieldset>
<legend>Anmäl Intresse:</legend>
<div class="row">
<div class="col-6">
<input type="text" class="form-control" placeholder="Namn" name="name" value="<?php echo esc_attr($_POST['name']); ?>">
</div>
<div class="col-6">
<input type="tel" class="form-control" placeholder="Telefonnummer" name="phone" value="<?php echo esc_attr($_POST['phone']); ?>">
</div>
</div>
<div class="row">
<div class="col">
<input type="email" class="form-control" placeholder="E-post" name="email" value="<?php echo esc_attr($_POST['email']); ?>">
</div>
<div class="col">
<input class="form-control" type="text" placeholder="<?php the_field('fb_8_1_plats'); ?> <?php the_field('fb_8_1_startdatum'); ?>" readonly name="plats_datum">
</div>
</div>
<div class="row">
<div class="col">
<div class="form-group">
<label for="meddelande1">Meddelande:</label>
<textarea class="form-control" rows="3" name="message" value="<?php echo esc_attr($_POST['message']); ?>" id="meddelande1"></textarea>
</div>
</div>
</div>
<input type="hidden" name="submitted" value="1">
<button type="submit" name="submitButton" class="btn btn-primary float-right">Skicka intresseanmälan</button>
</fieldset>
</form>
I really can't figure out what is wrong, I spent two full days just googling, trying and failing last weekend. After that I gave up and haven't looked at at for a week. Please help!
Edit: It doesn't load index.php, the path is still the same but it uses the template for index.php

PHP Contact Form 403 Error

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.';
?>

Bootstrap and PHP contact form display blank page when clicking submit [duplicate]

This question already has answers here:
PHP code is not being executed, but the code shows in the browser source code
(35 answers)
"Notice: Undefined variable", "Notice: Undefined index", "Warning: Undefined array key", and "Notice: Undefined offset" using PHP
(29 answers)
PHP mail function doesn't complete sending of e-mail
(31 answers)
Closed 5 years ago.
Hii guys I need some help.
When I try and test my bootstrap form, it displays a white screen. Here's my code.NB Am newbie to web developing, #ExcuseMyFrenchThough
Here is my index.html
<html>
<div class="container">
<div class="row">
<div class="col-md-6 col-md-offset-3" id="offer">
<h2 id="form"> LET'S WORK ? </h2>
</div>
<div class="col-md-6 col-md-offset-3">
<form role="form" method="post" action="contact.php">
<div class="form-group">
<input type="text" class="form-control" placeholder="Enter Your Name">
<?php echo "<p class='text-danger'>$errName</p>";?>
</div>
<div class="form-group">
<input type="email" class="form-control" id="exampleInputEmail1" placeholder="Enter Your Email">
<?php echo "<p class='text-danger'>$errEmail</p>";?>
</div>
<div class="form-group">
<textarea class="form-control" id="textarea1" rows="3" placeholder="Enter Your Message here"> </textarea>
<?php echo "<p class='text-danger'>$errMessage</p>";?>
</div>
<div class="form-group">
<button type="submit" class="default-submit btn btn-large propClone bg-fast-pink btn-circle font-weight-300 text-white tz-text">SEND MESSAGE</button>
</div>
<div class="form-group">
<div class="col-sm-10 col-sm-offset-2">
<?php echo $result; ?>
</div>
</div>
</form>
</div>
</div>
</div>
PHP CODE [CONTACT.PHP]
<?php
if (isset($_POST["submit"])) {
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
/*$human = intval($_POST['human']); */
$from = 'Geofrey Zellah';
$to = 'hotbonge#gmail.com';
$subject = 'Message from Geofrey Zellah ';
$body = "From: $name\n E-Mail: $email\n Message:\n $message";
// Check if name has been entered
if (!$_POST['name']) {
$errName = 'Please enter your name';
}
// Check if email has been entered and is valid
if (!$_POST['email'] || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$errEmail = 'Please enter a valid email address';
}
//Check if message has been entered
if (!$_POST['message']) {
$errMessage = 'Please enter your message';
}
/*
//Check if simple anti-bot test is correct
if ($human !== 5) {
$errHuman = 'Your anti-spam is incorrect';
} */
// If there are no errors, send the email
if (!$errName && !$errEmail && !$errMessage /*&& !$errHuman*/) {
if (mail ($to, $subject, $body, $from)) {
$result='<div class="alert alert-success">Thank You! I will be in touch</div>';
} else {
$result='<div class="alert alert-danger">Sorry there was an error sending your message. Please try again later</div>';
}
}
}
?>
Screenshot of what I get after I click submit on my page, NB live not local
anyone ?
The submit variable is never set in your form. Note the button is now an input of the type submit with the name attribute of submit.
Also your other form variables were not set.
You were never echoing anything. So i put an echo in your last condition.
If you want the form to display after submitting the form, you need to rename your index.html to index.php and include contact.php at the top. See below.
If you just plainly check if a $_POST variable is true, PHP will throw E_NOTICE errors. So best wrap the variable into the isset() (as in is this variable set) function. See below.
I refactored to prevent E_NOTICE errors and commented the changes.
contact.php
<?php
if (isset($_POST["submit"])) {
$error = [];
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
/*$human = intval($_POST['human']); */
$from = 'Geofrey Zellah';
$to = 'hotbonge#gmail.com';
$subject = 'Message from Geofrey Zellah ';
$body = "From: $name\n E-Mail: $email\n Message:\n $message";
// Check if name has been entered
if (!isset($_POST['name']) || strlen($_POST['name']) === 0) {
$error['name'] = 'Please enter your name';
}
// Check if email has been entered and is valid
if (!isset($_POST['email']) || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$error['email'] = 'Please enter a valid email address';
}
//Check if message has been entered
if (!isset($_POST['message']) || strlen($_POST['name']) === 0) {
$error['message'] = 'Please enter your message';
}
/*
//Check if simple anti-bot test is correct
if ($human !== 5) {
$errHuman = 'Your anti-spam is incorrect';
} */
// If there are no errors, send the email
if (empty($error)) {
if (mail ($to, $subject, $body, $from)) {
$result='<div class="alert alert-success">Thank You! I will be in touch</div>';
} else {
$result='<div class="alert alert-danger">Sorry there was an error sending your message. Please try again later</div>';
}
}
}
?>
index.php <-- Note the change of file extension
<?php include 'contact.php';?>
<div class="container">
<div class="row">
<div class="col-md-6 col-md-offset-3" id="offer">
<h2 id="form"> LET'S WORK ? </h2>
</div>
<div class="col-md-6 col-md-offset-3">
<form role="form" method="post">
<div class="form-group">
<input name="name" type="text" class="form-control" placeholder="Enter Your Name">
<?php if(isset($error['name'])) echo '<p class="text-danger">'.$error['name'].'</p>'; ?>
</div>
<div class="form-group">
<input name="email" type="email" class="form-control" id="exampleInputEmail1" placeholder="Enter Your Email">
<?php if(isset($error['email'])) echo '<p class="text-danger">'.$error['email'].'</p>'; ?>
</div>
<div class="form-group">
<textarea name="message" class="form-control" id="textarea1" rows="3" placeholder="Enter Your Message here"> </textarea>
<?php if(isset($error['message'])) echo '<p class="text-danger">'.$error['message'].'</p>'; ?>
</div>
<div class="form-group">
<input name="submit" type="submit" class="default-submit btn btn-large propClone bg-fast-pink btn-circle font-weight-300 text-white tz-text">SEND MESSAGE</input>
</div>
<div class="form-group">
<div class="col-sm-10 col-sm-offset-2">
<?php if(isset($result)) echo $result; ?>
</div>
</div>
</form>
</div>
</div>
</div>
UPDATE
If you do not want a reload of the page when submitting the form, you will need some jQuery ajax action and alter your HTML and PHP file.
First remove the first line of your index.php that we added before:
<?php include 'contact.php';?><!-- Remove this one -->
You do not want the file to be included, but rather send data to it.
Next edit the HTML file and include jQuery library underneath your HTML (common practice to do JS stuff below HTML). Then alter your PHP file accordingly.
So your new HTML:
<div class="container">
<div class="row">
<div class="col-md-6 col-md-offset-3" id="offer">
<h2 id="form"> LET'S WORK ? </h2>
</div>
<div class="col-md-6 col-md-offset-3">
<form role="form" name="contact" method="post">
<div class="form-group">
<input name="name" type="text" class="form-control" placeholder="Enter Your Name" value="test">
</div>
<div class="form-group">
<input name="email" type="email" class="form-control" id="exampleInputEmail1" placeholder="Enter Your Email" value="giroteam#localhost.com">
</div>
<div class="form-group">
<textarea name="message" class="form-control" id="textarea1" rows="3" placeholder="Enter Your Message here">test </textarea>
</div>
<div class="form-group">
<input name="submit" type="submit" class="default-submit btn btn-large propClone bg-fast-pink btn-circle font-weight-300 text-white tz-text" value="SEND MESSAGE">
</div>
<div class="form-group" id="result">
</div>
</form>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){ // launch when DOM is fully loaded
$('form[name="contact"]').submit(function(event){ // fire when you hit submit
event.preventDefault(); // prevent default form submission since you want to send data via ajax
$('#result').html('');
$('.alert').remove();
var values = $(this).serialize();
// Post form data to your contact.php script and work with response
$.ajax({
url: "contact.php",
type: "POST",
data: values ,
success: function (response) {
if(response.success) {
$('#result').html('<div class="alert alert-success">'+response.success+'</div>');
}
if(response.error_form) {
$.each( response.error_form, function( key, value ) {
$('input[name="'+key+'"]').parent().append('<p class="help-block text-danger">'+value+'</p>');
});
}
if(response.error_mail) {
$('#result').html('<div class="alert alert-danger">'+response.error_mail+'</div>');
}
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
});
});
</script>
And finally the changed PHP:
<?php
ini_set('display_errors',0);
$result = [];
// Check if name has been entered
if (!isset($_POST['name']) || strlen($_POST['name']) === 0) {
$result['error_form']['name'] = 'Please enter your name';
}
// Check if email has been entered and is valid
if (!isset($_POST['email']) || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$result['error_form']['email'] = 'Please enter a valid email address';
}
//Check if message has been entered
if (!isset($_POST['message']) || strlen($_POST['message']) === 0) {
$result['error_form']['message'] = 'Please enter your message';
}
/*
//Check if simple anti-bot test is correct
if ($human !== 5) {
$errHuman = 'Your anti-spam is incorrect';
} */
// If there are no errors, send the email
if (empty($result['error_form'])) {
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
/*$human = intval($_POST['human']); */
$from = 'Geofrey Zellah';
$to = 'hotbonge#gmail.com';
$subject = 'Message from Geofrey Zellah ';
$body = "From: $name\n E-Mail: $email\n Message:\n $message";
if (mail ($to, $subject, $body, $from)) {
$result['success']='Thank You! I will be in touch';
} else {
$result['error_mail']='Sorry there was an error sending your message. Please try again later';
}
}
header('Content-type: application/json'); // tell browser what to expect
echo json_encode($result); // encode array to json object so javascript can work with it
I made such an elaborate example since many people decide to go ajax once they are successful in sending a regular form but notice that the page reloads ;)
I get what you want to achieve. You want to submit this form and if something is wrong, you want to show some error messages.
What has happened in your case is that, when you submit your form, it gets submitted to contact.php. Your browser will show what you return from the contact.php file. Since your contact.php do not include any HTML content and you don't write anything either, returned page doesn't include anything.
You have two options.
First way:
echo the error messages to the contact.php file. Add the following to the end of contact.php file.
echo $result;
This way, when someone submit your form. You will direct him to a new page which only have some line saying whether there was error or successful.
Second way
Move that logic to your index.html. You have to rename it to index.php. Then set the form to submit to the same page.
<form .... action="">
This will submit the form to the current page, which is index.php. Then, put your logic in contact.php at top of your index.php.

Simple PHP Contact Form - 2 Days of Pain

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"]));

Categories