I am using a custom php captcha on a website and I am unable to get the php that send the email to check if the captcha was completed successfully. Here is the code:
Form:
<form method="POST" name="contact_form" action="/templates/onlinespark/contact-form-handler.php">
<label for="name">Name: </label>
<input type="text" name="name" value="<?php echo htmlentities($name); ?>">
<label for='email'>Email: </label>
<input type="text" name="email" value="<?php echo htmlentities($visitor_email); ?>">
<label for="phone">Phone: </label>
<input type="text" name="phone" value='<?php echo htmlentities($phone); ?>'>
<label for="message">Message:</label>
<textarea name="message" rows="8" cols="30"><?php echo htmlentities($user_message); ?></textarea>
<label><img src="/templates/onlinespark/captcha.php"></label>
<input type="text" name="code">
<input type="submit" value="Submit" name="submit" class="quoteButton">
</form>
PHP: contact-form-hander.php
<?php
if (isset($_POST['submit'])) {
$error = "";
if (!empty($_POST['name'])) {
$name = $_POST['name'];
} else {
$error .= "You didn't type in your name. <br />";
}
if (!empty($_POST['phone'])) {
$name = $_POST['phone'];
} else {
$error .= "You didn't enter your phone. <br />";
}
if (!empty($_POST['email'])) {
$email = $_POST['email'];
if (!preg_match("/^[a-z0-9]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i", $email)){
$error .= "The e-mail address you entered is not valid. <br/>";
}
} else {
$error .= "You didn't type in an e-mail address. <br />";
}
if (!empty($_POST['message'])) {
$message = $_POST['message'];
} else {
$error .= "You didn't type in a message. <br />";
}
if(($_POST['code']) == $_SESSION['code']) {
$code = $_POST['code'];
} else {
$error .= "The captcha code you entered does not match. Please try again. <br />";
}
if (empty($error)) {
$from = 'From: ' . $name . ' <' . $email . '>';
$to = "mail#email.com";
$subject = "New contact form message";
$content = $name . " has sent you a message: \n" . $message;
$success = "<h3>Thank you! Your message has been sent!</h3>";
mail($to,$subject,$content,$from);
}
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>ERROR - Please fill in all fields!</title>
</head>
<body>
<!-- This page is displayed only if there is some error -->
<h1>ERROR - Please go back and fill in all fields!</h1>
<?php
if (!empty($error)) {
echo '<p class="error"><strong>Your message was NOT sent<br/> The following error(s) returned:</strong><br/>' . $error . '</p>';
} elseif (!empty($success)) {
echo $success;
}
?>
</body>
</html>
Basically I need the external php file that sends the mail to check to see if the captcha was completed correctly before it sends the mail. At the moment it seems to be ignoring the captcha all together. What do I need to do?
Thanks!
In your form:
<?php
session_start(); //important!
$_SESSION['code'] = sha1('Same text as in the image');
?>
<!--form goes here-->
In your contact-form-hander.php:
//At top of your code
session_start();
//code
if(sha1($_POST['code']) == $_SESSION['code']) {
$code = $_POST['code'];
} else {
$error .= "The captcha code you entered does not match. Please try again. <br />";
}
//code
The sha1() function converts the given value in a hash value wich can't be cracked.
You should use this because the session storage can easely be accessed using a develpment tool, and a bot could spam your form(because he can read in the session storge). So encode the text in the captcha and compare it with the encoded value of the entered text.
The session_start() function creates or resumes a session.
One way is to use a key/value pair when using captchas. Get a random image (key) and compare the value thereof...
Related
This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
Closed 5 years ago.
I have form in my site example.com/pp.php and that formĀ“s action is pp.php because that script is not some external file, but inside of that page. The problem is I need to put header("Location: http://example.com/pp.php#contactForm"); because after pressing Send button I want to reload page on exact position which is /pp.php#contactForm. But header Location is not working.
<form action="pp.php" method="post">
<label>Name:</label>
<input type="text" name="name" value="<?php if($_POST['name']) {
echo $_POST['name']; } ?>" />
<label>Email:</label>
<input type="text" name="email" value="<?php if($_POST['email'])
{ echo $_POST['email']; } ?>" />
<label>Message:</label><br />
<textarea name="message" rows="20" cols="20"><?php
if($_POST['message']) { echo $_POST['message']; } ?></textarea>
<label><img src="captcha.php"></label>
<input type="text" name="code"> <br />
<input type="submit" class="submit" name="submit" value="Send
message" />
</form>
This is php
<?php
if (isset($_POST['submit'])) {
$error = "";
if (!empty($_POST['name'])) {
$name = $_POST['name'];
} else {
$error .= "You didn't type in your name. <br />";
}
if (!empty($_POST['email'])) {
$email = $_POST['email'];
if (!preg_match("/^[a-z0-9]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*
(\.[a-z]{2,3})$/i", $email)){
$error .= "The e-mail address you entered is not valid. <br/>";
}
} else {
$error .= "You didn't type in an e-mail address. <br />";
}
if (!empty($_POST['message'])) {
$message = $_POST['message'];
} else {
$error .= "You didn't type in a message. <br />";
}
if(($_POST['code']) == $_SESSION['code']) {
$code = $_POST['code'];
} else {
$error .= "The captcha code you entered does not match. Please try
again. <br />";
}
if (empty($error)) {
$from = 'From: ' . $name . ' <' . $email . '>';
$to = "mail#gmail.com";
$subject = "New contact form message";
$content = $name . " has sent you a message: \n" . $message;
$success = "<h3>Thank you! Your message has been sent!</h3>";
mail($to,$subject,$content,$from);
}
}
?>
<?php
if (!empty($error)) {
echo '<p class="error"><strong>Your message was NOT sent<br/> The
following error(s) returned:</strong><br/>' . $error . '</p>';
} elseif (!empty($success)) {
echo $success;
}
header("Location: http://example.com/pp.php#contactForm");
?>
You can't redirect with header() after outputting to the DOM:
Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP.
As such, you'll need to remove the echo statements in your lines:
if (!empty($error)) {
echo '<p class="error"><strong>Your message was NOT sent<br/> The
following error(s) returned:</strong><br/>' . $error . '</p>';
} elseif (!empty($success)) {
echo $success;
}
Before calling:
header("Location: http://example.com/pp.php#contactForm");
Try this:
header('Location: pp.php#contactForm');
And make sure you do not output any html tag through anyway before this line.
like the echo $success;
I have a simple contact form with some PHP validation attached to it. However, when a field if left blank and the form is thrown one of these errors, it redirects to a blank page and just echos out the error on a blank screen. How would I go about keeping these errors on the same page? The errors don't have to validate instantly, just when someone clicks send. Optimally it would just direct to the contact form page and have an added string of text about the form that tells the user that there was an error.
PHP
<?php if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = trim($_POST["name"]);
$email = trim($_POST["email"]);
$subject = trim($_POST["subject"]);
$message = trim($_POST["message"]);
if ($name == "") {
// header("Location: contact.php");
echo "You must speciy a value for name.";
exit;
}
if ($email == "") {
// header("Location: contact.php");
echo "You must speciy a value for email.";
exit;
}
if ($subject == "") {
// header("Location: contact.php");
echo "You must speciy a value for subject.";
exit;
}
if ($message == "") {
// header("Location: contact.php");
echo "You must speciy a value for message.";
exit;
}
foreach( $_POST as $value ) {
if( stripos($value,'Content-Type:') !== FALSE ){
echo "There was a problem with the information you entered.";
exit;
}
}
if ($_POST["address"] != "") {
echo "Your submission has an error.";
exit;
}
require_once("class.phpmailer.php");
$mail = new PHPMailer();
if (!$mail-> ValidateAddress($email)){
echo "You must specify a valid email address";
exit;
}
$email_body = "";
$email_body = $email_body . "Name: " . $name . "<br>";
$email_body = $email_body . "Email: " . $email . "<br>";
$email_body = $email_body . "Subject: " . $subject . "<br>";
$email_body = $email_body . "Message: " . $message . "<br>";
$mail->setFrom($email, $name);
$mail->addAddress('email#gmail.com', 'Staff');
$mail->Subject = "Contact Form | " . $name;
$mail->msgHTML($email_body);
//send the message, check for errors
if (!$mail->send()) {
echo "There was a problem sending the email: " . $mail->ErrorInfo;
exit;
}
header("Location: contact.php?status=thanks");
exit;
}
?>
HTML
<div id="contact-form">
<div class="container">
<div class="row">
<div class="col-md-6">
<form class="form" method="post">
<p class="name">
<div id="label"><label for="name">Name</label></div>
<input type="text" name="name" id="name" placeholder="John Doe" />
</p>
<p class="email">
<div id="label"><label for="email">Email</label></div>
<input type="text" name="email" id="email" placeholder="mail#example.com" />
</p>
<p class="subject">
<div id="label"><label for="subjext">Subject</label></div>
<select name="subject" id="subject">
<option></option>
<option>Request for Consultation</option>
<option>Ordering a Service</option>
<option>Just to Say Hello</option>
<option>Other</option>
</select>
</p>
<p class="message">
<div id="label"><label for="message">Message</label></div>
<textarea name="message" id="message" placeholder="Write something to us" /></textarea>
</p>
<div id="label" class="address" style="display:none !important"><label for="address">Email</label>
<input type="text" name="address" id="address" placeholder="123 Elm Street" />
<p>If you're a human, please leave this field blank.</p>
</div>
<p class="submit">
<input type="submit" value="Send" class="btn-blue btn-submit"/>
</p>
</form>
</div>
</div>
</div>
Two basic options...
(1) Include the error message as part of the URL.
header("Location: contact.php?error=" . urlencode("You must specify a value for name."));
You can then, in contact.php add a echo $_GET["error"]; in the appropriate place.
Biggest downside here is potential for abuse. A message included in the URL can be changed by the user, or anyone to display anything. Someone malicious might change the message to confuse or abuse a user.
(2) Use sessions to store the error message.
session_start();
$_SESSION["error"] = "You must specific a value for name.";
And then on contact.php, at the top add a session_start(); and somewhere in the page add...
if ($_SESSION["error"] != "") {
echo $_SESSION["error"];
$_SESSION["error"] = "";
}
There are more ways, but this should get you started.
You can actually do this with PHP if you do not have a great knowledge of Javascript or AJAX. You have 2 options: one of them is overcomplicated, but I will give you both anyway.
Option #1:
Send the form to the same page.
Change the action of the form to send it to whatever page the form itself is on. Then, when you want to do the error messages, instead of doing
echo "insert error message here";
for the first error msg, in your case if they left name empty, you want to do
$errormsg = "insert error message here";
for every other validation, you want to do
$errormsg .= "insert error message here";
then, just echo out the
$errormsg
if it is not null.
Option #2
This option is very overdone. It has the same concept as above, but it adds support for if you want to have the form on the other page.
Make sure you have
session_start();
on the top of both the form page and the form validation php page.
now, for the first errormsg that occurs:
$_SESSION['errormsg'] = "insert error message here";
For every other error msg after that, you can do
$_SESSION['errormsg'] .= "insert error message here";
as we did before.
I am an eager novice with PHP so please forgive my errors as I am learning as I go. Basically, I am building a simple contact form for my website and have successfully been able to have the form send the user's first and last name, subject, email address and message. I am using a second file, "form_process.php" to process the form data from "index.php".
The problem is that the email address does not seem to be validating and will send any words typed. I would greatly appreciate it if some more seasoned eyes could take a look and help me sort this out. Thank you in advance.
Michael.
HTML:
<div id="form">
<form action="form_process.php" method="post" enctype="multipart/form-data">
<p>
<input type="text" maxlength="100" size="50" name="fName" value="<?php echo $stored_fName;?>" placeholder="First Name" />
</p>
<p>
<input type="text" maxlength="100" size="50" name="lName" value="<?php echo $stored_lName;?>" placeholder="Last Name" />
</p>
<p>
<input type="text" maxlength="80" size="50" name="email" value="<?php echo $stored_email;?>" placeholder="Email Address" />
</p>
<p>
<input type="text" maxlength="100" size="50" name="subject" value="<?php echo $stored_subject;?>" placeholder="Subject" />
</p>
<p>
<textarea name="message" rows="6" cols="38" placeholder="Message"></textarea>
</p>
<br />
<input type="submit" value="Submit" name="submit" />
<input type="reset" value="Clear" name="clear">
</form>
</div>
<!-- form ends -->
PHP: "form_process.php"
<?php
session_start();
// Report all PHP errors
error_reporting(E_ALL);
//use $_POST to to store data from submitted form into these variables
$fName = check_input($_POST['fName']);
$lName = check_input($_POST['lName']);
$sender = check_input($_POST['email']);
$subject = check_input($_POST['subject']);
$message = check_input($_POST['message']);
//check_input function to strip unnessessary characters and sanitize user data
function check_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$name = $fName ." ". $lName;//concatenating first and last names to new name variable
$sanitizedEmail = filter_var($sender, FILTER_SANITIZE_EMAIL);
//generates error messages on index.php if form fields left blank
if ($fName == ''){
header("Location:index.php?message=1");
exit();
}
if ($lName == ''){
header("Location:index.php?message=2");
exit();
}
if ($sender == ''){
header("Location:index.php?message=3");
exit();
}
if ($subject == ''){
header("Location:index.php?message=4");
exit();
}
if ($message == ''){
header("Location:index.php?message=5");
exit();
}
//headers
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
$headers .= $name . "\r\n";
$headers .= "From:" . " " . $sanitizedEmail . "\r\n";
//mail function
$to = "me#myemail.com";
$subject = $subject;
$message = $message;
//send message
$send_message = mail($to,$subject,$message,$headers);
if($send_message){
header("Location:index.php?message=6");
}else {
header("Location:index.php?message=9");
exit();
}
?>
"index.php" error messages:
<?php
//all fields empty until user inputs data for session to store
$stored_fName = '';//init as NULL
$stored_lName = '';//init as NULL
$stored_email = '';//init as NULL
$stored_subject = '';//init as NULL
$stored_message = '';//init as NULL
//session data used to repopulate form fields if any info is missing or incorrect
if (isset($_SESSION['fName'])){
$stored_fName = $_SESSION['fName'];
}
if (isset($_SESSION['lName'])){
$stored_lName = $_SESSION['lName'];
}
if (isset($_SESSION['email'])){
$stored_email = $_SESSION['email'];
}
if (isset($_SESSION['subject'])){
$stored_subject = $_SESSION['subject'];
}
if (isset($_SESSION['message'])){
$stored_message = $_SESSION['message'];
}
//error messages displayed to user if text fields have been left blank
$_GET['message'];
if ($_GET['message'] == 1) {//first name
echo "<strong>Please type your first name.</strong>";
}
if ($_GET['message'] == 2) {//last name
echo "<strong>Please type your last name.</strong>";
}
if ($_GET['message'] == 3){//email address
echo "<strong>Please type an email address.</strong>";
}
if ($_GET['message'] == 4){//subject
echo "<strong>Please type a subject.</strong>";
}
if ($_GET['message'] == 5){//message text
echo "<strong>Please type your message.</strong>";
}
if ($_GET['message'] == 6){//message success from form_process.php
echo "<strong>Your message was sent successfully. Thank you.</strong>";
}
if ($_GET['message'] == 9){
echo "<strong>I'm sorry but your message was not sent. Please try again, thank you.</strong>";
}
?>
You should be using it like this:
if(filter_var($email, FILTER_VALIDATE_EMAIL)){
// is email
$sender = $email;
}else{
// isn't email
$sender = '';
}
Read more about PHP Validate Filters
I have an email form on a website that sends the form data to an external php file (contact-form-handler.php) I have recently tried to add a captcha however I have been unsuccessful in getting the external php file to check if the captcha code was entered correctly.. At the moment it says that it is incorrect even when I enter the correct code.
The website is bathroomdesignperth.com.au
Form code:
<?php
$_SESSION['code'] = sha1('Same text as in the image');
?>
<form method="POST" name="contact_form" action="/templates/onlinespark/contact-form-handler.php">
<label for='name'>Name: </label>
<input type="text" name="name" value='<?php echo htmlentities($name) ?>'>
<label for='email'>Email: </label>
<input type="text" name="email" value='<?php echo htmlentities($visitor_email) ?>'>
<label for='phone'>Phone: </label>
<input type="text" name="phone" value='<?php echo htmlentities($phone) ?>'>
<label for='message'>Message:</label>
<textarea name="message" rows=8 cols=30><?php echo htmlentities($user_message) ?></textarea>
<label><img src="/templates/onlinespark/captcha.php"></label>
<input type="text" name="code">
<input type="submit" value="Submit" name='submit' class="quoteButton">
</form>
Php code:
<?php
if (isset($_POST['submit'])) {
$error = "";
if (!empty($_POST['name'])) {
$name = $_POST['name'];
} else {
$error .= "You didn't type in your name. <br />";
}
if (!empty($_POST['phone'])) {
$name = $_POST['phone'];
} else {
$error .= "You didn't enter your phone. <br />";
}
if (!empty($_POST['email'])) {
$email = $_POST['email'];
if (!preg_match("/^[a-z0-9]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i", $email)){
$error .= "The e-mail address you entered is not valid. <br/>";
}
} else {
$error .= "You didn't type in an e-mail address. <br />";
}
if (!empty($_POST['message'])) {
$message = $_POST['message'];
} else {
$error .= "You didn't type in a message. <br />";
}
if(sha1($_POST['code']) == $_SESSION['code']) {
$code = $_POST['code'];
} else {
$error .= "The captcha code you entered does not match. Please try again. <br />";
}
if (empty($error)) {
$from = 'From: ' . $name . ' <' . $email . '>';
$to = "mail#email.com.au";
$subject = "New contact form message";
$content = $name . " has sent you a message: \n" . $message;
$success = "<h3>Thank you! Your message has been sent!</h3>";
mail($to,$subject,$content,$from);
}
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>ERROR - Please fill in all fields!</title>
</head>
<body>
<!-- This page is displayed only if there is some error -->
<h1>ERROR - Please go back and fill in all fields!</h1>
<?php
if (!empty($error)) {
echo '<p class="error"><strong>Your message was NOT sent<br/> The following error(s) returned:</strong><br/>' . $error . '</p>';
} elseif (!empty($success)) {
echo $success;
}
?>
</body>
</html>
Send the correct answer to the captcha in an encoded form to the external php file via POST.
<?php $salt = 'some-random-text'; ?>
<input type="text" name="code" />
<input type="hidden" name="code_key" value="<?php echo sha1('Text in the image' . $salt); ?>" />
In the PHP code, instead of using the session value, check the posted 'code_key'.
$salt = 'some-random-text'; // same salt string as in the original file
if ($_POST['code_key'] == sha1($_POST['code'] . $salt)) {
// captcha is correct
} else {
// captcha is wrong
}
This works perfectly for captcha checks across different domains. Note that $salt parameter is for added security.
on my website I have an automatic contact formular, it runs on my localhost server, but if I load the File onto my Server it won't work. It seems like the submit doesn't work, it doesn't throw an error message it just reloads the page. I've done a lot of code review, but couldn`t find any issue until now.
The strange thing to me is, that the code works on my localhost but not on the server...
You can test it yourself here:
http://144.76.1.46/RequestStream.php
And heres the code:
<?php
$your_email ='censored#gmail.com';
session_start();
$errors = '';
$name = '';
$visitor_email = '';
$user_message = '';
if(isset($_POST['Submit']))
{
$name = $_POST['name'];
$visitor_email = $_POST['email'];
$user_message = $_POST['message'];
///------------Do Validations-------------
if(empty($name)||empty($visitor_email))
{
$errors .= "\n Name and Email are required fields. ";
}
if(IsInjected($visitor_email))
{
$errors .= "\n Bad email value!";
}
if(empty($_SESSION['6_letters_code'] ) ||
strcmp($_SESSION['6_letters_code'], $_POST['6_letters_code']) != 0)
{
//Note: the captcha code is compared case insensitively.
//if you want case sensitive match, update the check above to
// strcmp()
$errors .= "\n The captcha code does not match!";
}
if(empty($errors))
{
//send the email
$to = $your_email;
$subject="New form submission";
$from = $your_email;
$ip = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '';
$body = "A user $name submitted the contact form:\n".
"Name: $name\n".
"Email: $visitor_email \n".
"Message: \n ".
"$user_message\n".
"IP: $ip\n";
$headers = "From: $from \r\n";
$headers .= "Reply-To: $visitor_email \r\n";
mail($to, $subject, $body, $headers);
header('Location: thank-you.html');
}
}
// Function to validate against any email injection attempts
function IsInjected($str)
{
// censored
}
else
{
return false;
}
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Contact Us</title>
<!-- a helper script for vaidating the form-->
<script language="JavaScript" src="censored" type="text/javascript"></script>
</head>
<body>
<?php
if(!empty($errors)){
echo "<p class='err'>".nl2br($errors)."</p>";
}
?>
<div id='contact_form_errorloc' class='err'></div>
<form method="POST" name="contact_form"
action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>">
<p>
<label for='name'>Streamname: </label><br>
<input type="text" name="name" value='<?php echo htmlentities($name) ?>'>
</p>
<p>
<label for='email'>Your Email: (for possible further queries) </label><br>
<input type="text" name="email" value='<?php echo htmlentities($visitor_email) ?>'>
</p>
<p>
<label for='message'>Streamlink and explanation why he should be listed on Lol Streamgalleries: (preferably with links to reliable sources (such as leagepedia for example)</label> <br>
<textarea name="message" rows=8 cols=30><?php echo htmlentities($user_message) ?></textarea>
</p>
<p>
<img src="html-contact-form-captcha/captcha_code_file.php?rand=<?php echo rand(); ?>" id='captchaimg' ><br>
<label for='message'>Enter the code above here :</label><br>
<input id="6_letters_code" name="6_letters_code" type="text"><br>
<small>Can't read the image? click <a href='javascript: refreshCaptcha();'>here</a> to refresh</small>
</p>
<input type="submit" value="Submit" name='submit'>
</form>
<script language="JavaScript">
// Code for validating the form
// Visit http://www.javascript-coder.com/html-form/javascript-form-validation.phtml
// for details
var frmvalidator = new Validator("contact_form");
//remove the following two lines if you like error message box popups
frmvalidator.EnableOnPageErrorDisplaySingleBox();
frmvalidator.EnableMsgsTogether();
frmvalidator.addValidation("name","req","Please provide your name");
frmvalidator.addValidation("email","req","Please provide your email");
frmvalidator.addValidation("email","email","Please enter a valid email address");
</script>
<script language='JavaScript' type='text/javascript'>
function refreshCaptcha()
{
var img = document.images['captchaimg'];
img.src = img.src.substring(0,img.src.lastIndexOf("?"))+"?rand="+Math.random()*1000;
}
</script>
</body>
</html>
Edit:
the error console helped me a little bit, there was a reference error with the javascript file, fixed it now, but sadly still won't work.
you named your button submit but checking for $_POST['Submit']
try isset($_POST['submit'])
or
$_POST['submit'] == 'Submit'