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"]));
Related
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);
My PHP form isn't submitting successfully. I keep getting the custom error that I wrote ('Oops there was a problem. Please try again").
any help would be greatly appreciated. I'm totally new to PHP so I'm thinking maybe some of my php variables are linked wrong and arent connecting with my mailer-new.php file?
Thanks in advance,
<section class="form-body">
<form method="post" action="mailer-new.php" class="contact-form" >
<div class="row">
<?php
if ($_GET['success']== 1){
echo " <div class=\"form-messages success\"> Thank you!
your message has been sent. </div>";
}
if ($_GET['success']== -1){
echo " <div class=\"form-messages error\"> Opps there was a
problem. Please try again </div>";
};
?>
<div class="field name-box">
<input type="text" name="name" id="name" placeholder="Who
Are You?" required/>
<label for="name">Name</label>
<span class="ss-icon">check</span>
</div>
<div class="field email-box">
<input type="text" name="email" id="email"
placeholder="name#email.com" required/>
<label for="email">Email</label>
<span class="ss-icon">check</span>
</div>
<div class="field msg-box">
<textarea name="message" id="msg" rows="4"
placeholder="Your message goes here..."/></textarea>
<label for="message">Msg</label>
<span class="ss-icon">check</span>
</div>
<input class="button" type="submit" value="Send"/>
</div>
</form>
</section>
MAILER.PHP
<?php
// Get the form fields, removes html tags and 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 the data.
if (empty($name) OR empty($message) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
header("Location: http://www.conallen.ie/index.php?
success=-1#form");
exit;
}
// Set the recipient email address. Update this to YOUR desired email address.
$recipient = "allenconallen46#gmail.com";
// 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.
mail($recipient, $subject, $email_content, $email_headers);
// Redirect to the index.html page with success code
header("Location: http://www.conallen.ie/index.php?success=1#form");
?>
This code works correctly in my local machine, even though email is not sent response messages are coming correctly. The changes I have done is changed the host name and made the two lined header redirect into one line in the failed response. Also you have mentioned in the HTML the file name as action="mailer-new.php" and the file name mentioned in the question as MAILER.PHP. Are they same in the code?
To check whether the mail is sent or not remove the header redirect and update like this. If you are getting a failed response means mail is not configured in your server.
if(mail($recipient, $subject, $email_content, $email_headers)) {
echo "mail sent";
} else {
echo "mail sent failed";
}
Alternatively you can use the SMTP for sending email. You can use a library called PHP Mailer and can use any of the valid email address like a gmail account. Please have look at this question if that's the case
Sending email with PHP from an SMTP server
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.
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.