I'm just beginner when it comes to coding, don't judge.
I wanted to display a notification after I clicked the submit button or to display a notification if there is something wrong with the data I input with the form. But it seems that the notification was already displayed even if I just opened the file.
Here's the code:
<?php
// Only process POST reqeusts.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Get the form fields and remove whitespace.
$name = strip_tags(trim($_POST["name"]));
$name = str_replace(array("\r","\n"),array(" "," "),$name);
$email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
$message = trim($_POST["message"]);
// Check that data was sent to the mailer.
if ( empty($name) OR empty($message) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
// Set a 400 (bad request) response code and exit.
http_response_code(400);
echo "Oops! There was a problem with your submission. Please complete the form and try again.";
exit;
}
// Set the recipient email address.
// FIXME: Update this to your desired email address.
$recipient = "myemail#gmail.com";
// Set the email subject.
$subject = "Customer Inquiry";
// Build the email content.
$email_content = "Name: $name\n";
$email_content .= "Email: $email\n\n";
$email_content .= "Message:\n$message\n";
// Build the email headers.
$email_headers = "From: $name <$email>";
// Send the email.
if (mail($recipient, $subject, $email_content, $email_headers)) {
// Set a 200 (okay) response code.
http_response_code(200);
echo " Thank You! Your message has been sent.";
} else {
// Set a 500 (internal server error) response code.
http_response_code(500);
echo "Oops! Something went wrong and we couldn't send your message.";
}
} else {
// Not a POST request, set a 403 (forbidden) response code.
http_response_code(403);
echo "There was a problem with your submission, please try again.";
}
?>
Here's the form:
<div class="column">
<h3>Get in Touch</h3>
<form action="#" target="myIframe" id="contactUs" method="post">
<div class="field half first">
<label for="name">Name</label>
<input name="name" id="name" type="text" placeholder="Name">
</div>
<div class="field half">
<label for="email">Email</label>
<input name="email" id="email" type="email" placeholder="Email">
</div>
<div class="field">
<label for="message">Message</label>
<textarea name="message" id="message" rows="6" placeholder="Message"></textarea>
</div>
<input name="submit" type="submit" value="Send Message">
</form>
<?php include "mailer.php"?>
</div>
You're getting an error because of the else block at the end. When you're displaying the form it's a GET request, not POST, so the if condition is false. That shouldn't be treated as an error, you should just display the form when that happens.
Get rid of
else {
// Not a POST request, set a 403 (forbidden) response code.
http_response_code(403);
echo "There was a problem with your submission, please try again.";
}
Instead of
if ($_SERVER["REQUEST_METHOD"] == "POST") {
You should have
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['submit'])) {
isset($_POST['submit']) checks whether the form is submitted or not.
Related
I'm having an issue with my website. To give some context, I've worked on it using ReactJS for the front-end and Express for the back-end. BUT, my hosting provider doesn't support Node, so I had to change the back-end part to PHP. I only developed the contact form functionality.
I'm not sure if I'm missing something, but I would like to ask your opinion to continue due to I'm stuck.
Here's the front-end part for Contact.js:
import React, {Component} from 'react';
class Contact extends Component{
render(){
return(
<div>
<form id="contact-form" name="c-form" method="post" action="/mailer.php">
<div className="input-field">
<input
id="first_name"
type="text"
className="validate"
name="first_name"
required/>
<label for="first_name">Name</label>
</div>
<div className="input-field">
<input id="sub" type="text" className="validate" name="sub"/>
<label for="sub">Subject</label>
</div>
<div className="input-field">
<input id="email" type="email" className="validate" name="email" required/>
<label for="email">Email</label>
</div>
<div className="input-field">
<textarea
id="textarea1"
className="materialize-textarea"
name="message"
required></textarea>
<label for="textarea1">Message</label>
</div>
<div className="contact-send">
<button
id="submit"
name="contactSubmit"
type="submit"
value="Submit"
className="btn waves-effect">Send
</button>
</div>
</form>
</div>
)
}
}
export default Contact;
and also, the back-end part in the PHP file, mailer.php located under /src folder:
<?php
// Only process POST reqeusts.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Get the form fields and remove whitespace.
$name = strip_tags(trim($_POST["name"]));
$name = str_replace(array("\r","\n"),array(" "," "),$name);
$email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
$message = trim($_POST["message"]);
// Check that data was sent to the mailer.
if ( empty($name) OR empty($message) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
// Set a 400 (bad request) response code and exit.
http_response_code(400);
echo "Oops! There was a problem with your submission. Please complete the form and try again.";
exit;
}
// Set the recipient email address.
// FIXME: Update this to your desired email address.
$recipient = "*HERE I PLACED MY EMAIL*";
// 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";
// Build the email headers.
$email_headers = "From: $name <$email>";
// Send the email.
if (mail($recipient, $subject, $email_content, $email_headers)) {
// Set a 200 (okay) response code.
http_response_code(200);
echo "Thank You! Your message has been sent.";
} else {
// Set a 500 (internal server error) response code.
http_response_code(500);
echo "Oops! Something went wrong and we couldn't send your message.";
}
} else {
// Not a POST request, set a 403 (forbidden) response code.
http_response_code(403);
echo "There was a problem with your submission, please try again.";
}
?>
The result is:
POST http://www.*mywebsite.com*/mailer.php 400 (Bad Request)
Any suggestion or recommendation? Thanks in advance!
change mailer.php
$name = strip_tags(trim($_POST["name"]));
to
$name = strip_tags(trim($_POST["first_name"]));
This question already has answers here:
How do I make a redirect in PHP?
(34 answers)
Closed 2 years ago.
I have a form on my main page. It sends messages fine, and I get them in email, but how can I get the mailer.php to redirect to the main index page of my site? Here is mailer.php currently;
<?php
// Only process POST reqeusts.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Get the form fields and remove whitespace.
$name = strip_tags(trim($_POST["name"]));
$name = str_replace(array("\r","\n"),array(" "," "),$name);
$email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
$message = trim($_POST["message"]);
// Check that data was sent to the mailer.
if ( empty($name) OR empty($message) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
// Set a 400 (bad request) response code and exit.
http_response_code(400);
echo "Oops! There was a problem with your submission. Please complete the form and try again.";
exit;
}
// Set the recipient email address.
// FIXME: Update this to your desired email address.
$recipient = "removed for privacy";
// 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";
// Build the email headers.
$email_headers = "From: $name <$email>";
// Send the email.
if (mail($recipient, $subject, $email_content, $email_headers)) {
// Set a 200 (okay) response code.
http_response_code(200);
echo "Thank You! Your message has been sent.";
} else {
// Set a 500 (internal server error) response code.
http_response_code(500);
echo "Oops! Something went wrong and we couldn't send your message.";
}
} else {
// Not a POST request, set a 403 (forbidden) response code.
http_response_code(403);
echo "There was a problem with your submission, please try again.";
}
?>
The form is at the bottom of my main index page of my website, I would like it to go back there automatically, if that's possible. Here is the HTML:
<div class="form">
<div id="sendmessage">Your message has been sent. Thank you!</div>
<div id="errormessage"></div>
<form id="ajax-contact" method="post" action="mailer.php">
<div class="field">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
</div>
<div class="field">
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
</div>
<div class="field">
<label for="message">Message:</label>
<textarea id="message" name="message" required></textarea>
</div>
<div class="field">
<button type="submit">Send</button>
</div>
</form>
Use header() to redirect to another page on success.
PHP Manual on header():
https://www.php.net/manual/en/function.header.php
// Send the email.
if (mail($recipient, $subject, $email_content, $email_headers)) {
//Now redirect to your index.php page and display your success message on your index page.
$url = 'http://' . $_SERVER['HTTP_HOST']; // Get the server
$url .= rtrim(dirname($_SERVER['PHP_SELF']), '/\\'); // Get the current directory
$url .= 'index.php?success'; // <-- Your relative path with a success post through url
header('Location: ' . $url, true, 302);
exit;
} else {
// Set a 500 (internal server error) response code.
http_response_code(500);
echo "Oops! Something went wrong and we couldn't send your message.";
}
Then on your index page, use
if(isset($_GET['success'])){
$success = "Thank You! Your message has been sent."; // Display this where you want your user to see it.
}
to display the success message
You can also have a redirect URL as a query string when you submit your form by adding
<form id="ajax-contact" method="post" action="mailer.php?return=CURRENTURL">
Then
if (mail($recipient, $subject, $email_content, $email_headers)) {
// Set a 200 (okay) response code.
header('Location: ' . $_GET['return'], true, 302);
} else {
// Set a 500 (internal server error) response code.
http_response_code(500);
echo "Oops! Something went wrong and we couldn't send your message.";
}
I want to integrate a recaptcha to my functioning contact form using PHP. The PHP form is already set, so I figured I should go that route. I believe
I have all necessary variables and parameters are set, I just need to know where exactly to place the final recaptcha verification in my PHP form.
I've tried several iterations of the code, but it essentially short-circuits and ruins the function of the existing code.
HTML:
<form action="php/contactform.php" method="post" role="form" class="contactForm" id="contactForm">
<div class="form-group">
<input type="text" name="name" class="form-control" id="name" placeholder="Your Name" data-rule="minlen:4" required />
</div>
<div class="form-group">
<input type="email" class="form-control" name="email" id="email" placeholder="Your Email" data-rule="email" required />
</div>
<div class="form-group">
<input type="text" class="form-control" name="subject" id="subject" placeholder="Subject" data-rule="minlen:4" required />
</div>
<div class="form-group">
<textarea class="form-control" name="message" id="message" rows="5" data-rule="required" required placeholder="Message"></textarea>
</div>
<div class="g-recaptcha" data-sitekey="SITEKEYCODEALREADYHERE"></div>
<div class="text-center"><button type="submit" name="submit">Send Message</button></div>
</form>
PHP:
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Get the form fields and remove whitespace.
$name = strip_tags(trim($_POST["name"]));
$name = str_replace(array("\r","\n"),array(" "," "),$name);
$subject = strip_tags(trim($_POST["subject"]));
$subject = str_replace(array("\r","\n"),array(" "," "),$subject);
$email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
$message = trim($_POST["message"]);
// Check that data was sent to the mailer.
if ( empty($name) OR empty($subject) OR empty($message) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
// Set a 400 (bad request) response code and exit.
http_response_code(400);
echo "Oops! There was a problem with your submission. Please complete the form and try again.";
exit;
}
// Set the recipient email address.
// FIXME: Update this to your desired email address.
$recipient = "me#cbonilla.dev";
// Set the email subject.
$subject = "Subject: $subject";
// Build the email content.
$email_content = "Name: $name\n";
$email_content .= "Email: $email\n\n";
$email_content .= "Message:\n$message\n";
// Build the email headers.
$email_headers = "From: $name <$email>";
//reCAPTCHA Verification
$secretKey = "SECRETCODEALREADYHERE";
$responseKey = $_POST['g-recaptcha-response'];
$UserIP = $_SERVER['REMOTE_ADDR'];
$url = "https://www.google.com/recaptcha/api/siteverify?secret='.$secretkey.'&response='.$responseKey.'&remoteip='.$UserIP.'";
$response = file_get_contents($url);
$data = json_decode($response);
// Send the email.
if (mail($recipient, $subject, $email_content, $email_headers)) {
// Set a 200 (okay) response code.
http_response_code(200);
echo "Thank You! Your message has been submitted, fam.";
} else {
// Set a 500 (internal server error) response code.
http_response_code(500);
echo "Oops! Something went wrong and we couldn't send your message.";
}
} else {
// Not a POST request, set a 403 (forbidden) response code.
http_response_code(403);
echo "There was a problem with your submission, please try again.";
}
?>
I believe the final code snippet occurs after the "// Send the email." note. I've also already added the reCAPTCHA JS tag in the section.
You're missing the check. And this would go BEFORE the send message part. Something like this:
if(!empty($data["success"])) {
// You could put the actual sending of the mail in here. Or, not.
} else {
echo "Your captcha failed!";
exit();
}
The above would come right after your data = json_decode() line.
THAT answers your question. But, consider this. The doc for recaptcha (https://developers.google.com/recaptcha/docs/verify) says that you must use a POST when calling the api endpoint to verify the captcha. You can do this with a curl call, similar to the below:
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => 'https://www.google.com/recaptcha/api/siteverify',
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => [
'secret' => $secretKey,
'response' => $captcha,
'remoteip' => $_SERVER['REMOTE_ADDR']
],
CURLOPT_RETURNTRANSFER => true
]);
$response = curl_exec($ch);
curl_close($ch);
$data = json_decode($response);
So I need to implement an AJAX information submit form. I'm using this example built by the guys at Treehouse… http://blog.teamtreehouse.com/create-ajax-contact-form
First part of the question… How do I add new fields? I've tried editing the .php .js and .html, getting them all in line to what I believe is right but upon testing my solution fails.
The fields I require…
Name:
Location:
Post Code:
Date of Birth:
URL Link:
Message (200 words):
The second part… Can I run two of these on the same page?
Cheers in advance for any help! - you can email me garethyo#gmail.com if you want me to send code etc.
CODE BELOW —
<form id="ajax-contact" method="post" action="mailer.php">
<div class="field">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
</div>
<div class="field">
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
</div>
<div class="field">
<label for="link">Link:</label>
<input type="text" id="link" name="link" required>
</div>
<div class="field">
<label for="message">Message:</label>
<textarea id="message" name="message" required></textarea>
</div>
<div class="field">
<button type="submit">Send</button>
</div>
</form>
JS
$(formMessages).text(response);
// Clear the form.
$('#name').val('');
$('#email').val('');
$('#link').val('');
$('#message').val('');
})
.fail(function(data) {
// Make sure that the formMessages div has the 'error' class.
$(formMessages).removeClass('success');
$(formMessages).addClass('error');
PHP
<?php
// My modifications to mailer script from:
// http://blog.teamtreehouse.com/create-ajax-contact-form
// Added input sanitizing to prevent injection
// Only process POST reqeusts.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Get the form fields and remove whitespace.
$name = strip_tags(trim($_POST["name"]));
$name = str_replace(array("\r","\n"),array(" "," "),$name);
$email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
$message = trim($_POST["message"]);
// Check that data was sent to the mailer.
if ( empty($name) OR empty($message) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
// Set a 400 (bad request) response code and exit.
http_response_code(400);
echo "Oops! There was a problem with your submission. Please complete the form and try again.";
exit;
}
// Set the recipient email address.
// FIXME: Update this to your desired email address.
$recipient = "garethyo#gmail.com";
// Set the email subject.
$subject = "A Future Bubbler… $name ";
// Build the email content.
$email_content = "Name: $name\n";
$email_content .= "Email: $email\n\n";
$email_content .= "Link: $link\n";
$email_content .= "Message:\n$message\n";
// Build the email headers.
$email_headers = "From: $name <$email>";
// Send the email.
if (mail($recipient, $subject, $email_content, $email_headers)) {
// Set a 200 (okay) response code.
http_response_code(200);
echo "Thank You! Your message has been sent.";
} else {
// Set a 500 (internal server error) response code.
http_response_code(500);
echo "Oops! Something went wrong and we couldn't send your message.";
}
} else {
// Not a POST request, set a 403 (forbidden) response code.
http_response_code(403);
echo "There was a problem with your submission, please try again.";
}
?>
You never define $link. You need to add $link = trim($_POST['link']); before $message = trim($_POST["message"]);. – Sean Apr 4 at 20:50
— Sean, CEO Worldstar
I'm having trouble getting my contact form to work. I'm new to php and this is the first mailer I've created, so I could definitely use some help.
Here's my HTML form
<form id="ajax-contact" method="post" action="mailer.php">
<div class="column">
<label for="name">name</label>
<input type="text" id="name" name="name" required>
<label for="email">email address</label>
<input type="email" id="email" name="email" required>
</div>
<div class="column">
<label for="message">message</label>
<textarea id="message" required></textarea>
</div>
<button type="submit">Send</button>
</form>
Here's my mailer.php
<?php
// My modifications to mailer script from:
// http://blog.teamtreehouse.com/create-ajax-contact-form
// Added input sanitizing to prevent injection
// Only process POST reqeusts.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Get the form fields and remove whitespace.
$name = strip_tags(trim($_POST["name"]));
$name = str_replace(array("\r","\n"),array(" "," "),$name);
$email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
$message = trim($_POST["message"]);
// Check that data was sent to the mailer.
if ( empty($name) OR empty($message) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
// Set a 400 (bad request) response code and exit.
http_response_code(400);
echo "Oops! There was a problem with your submission. Please complete the form and try again.";
exit;
}
$recipient = "thomas.lacroix.e#gmail.com";
$subject = "New message from $name";
$email_content = "Name: $name\n";
$email_content .= "Email: $email\n\n";
$email_content .= "Message:\n$message\n";
$email_headers = "From: $name <$email>";
// Send the email.
if (mail($recipient, $subject, $email_content, $email_headers)) {
// Set a 200 (okay) response code.
http_response_code(200);
echo "Thank You!";
} else {
// Set a 500 (internal server error) response code.
http_response_code(500);
echo "Oops! Something went wrong.";
}
} else {
// Not a POST request, set a 403 (forbidden) response code.
http_response_code(403);
echo "There was a problem with your submission, please try again.";
}
?>
I've searched for people with similar problems and I believe I need to add something with my email host settings. Let's be honest, though, I don't know what I'm doing. Any help is greatly appreciated!
It looks like on your form you forgot to include the name for the textarea which is causing an undefined index in the code when trying to get $_POST['message']
<textarea name="message" id="message" required></textarea>
Doing the above resolved the issue in testing for me.