PHP 5 HTML 5 contact form - php

I am very new to website design/programming and learned allot of html, css and a bit of php over the past few weeks. This is my first post here, Wish me luck :)
I am attempting to create a mail form from what I have learned from various websites, the form works but I have an issue with sanitizing the input, I'm not sure if I am doing it correctly as I can still "inject" code into the fields.
<?php session_start(); ?>
<!DOCTYPE html>
<html>
<body>
<?php
$ip = $_SERVER['REMOTE_ADDR'];
$browser = $_SERVER['HTTP_USER_AGENT'];
if (isset($_POST['submit'])) {
$error = '';
// Name
$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
// Telephone Number
$phone= filter_var($_POST['phone'], FILTER_SANITIZE_NUMBER_INT);
// Email Address
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
$error = 'You have not entered a valid email address.<br/>';
}
// Message
$message = filter_var($_POST['message'], FILTER_SANITIZE_STRING);
if (empty($error)) {
$from = 'From: ' . $name . ' <' . $email . '>';
$to = 'YourEmailHere';
$subject = 'Message from Contact Form';
$content = $name . ' has sent you a message: \n' . $message . '\n\nPhone Number: ' . $phone . '\n\nIP: ' . $ip . '\nBrowser:' . $browser;
$success = '<h3>Thank you!<br /> Your message has been sent!</h3>';
//mail($to,$subject,$content,$from);
}
}
?>
<h1>Contact Form</h1>
<br/>
<?php
if (!empty($error)) {
echo '<p class="error"><strong>Your message was NOT sent<br/> The following error(s) returned:</strong><br/><br/>' . $error . '<br/><strong>Please try again.</strong><br/></p>';
} elseif (!empty($success)) {
echo $success;
}
?>
<form action="" method="post">
Name:
<input type="text" name="name" required placeholder="Name" value="<?php { echo $_POST['name']; } ?>"><br/>
Telephone:
<input type="text" name="phone" required placeholder="Telephone Number e.g.0123456789" value="<?php { echo $_POST['phone']; } ?>"><br/>
Email:
<input type="text" name="email" required placeholder="Email Address" value="<?php { echo $_POST['email']; } ?>"><br/>
Message:<br />
<textarea name="message" required placeholder="Message" rows="20" cols="20"><?php { echo $_POST['message']; } ?></textarea><br/>
<input type="submit" class="submit" name="submit" value="Send message">
<br/>
</form>
<!-- Below is Just for testing -->
<?php echo '<br/>Name : ' . $name . '<br/><br/>Phone : ' . $phone . '<br/><br/>Email : ' . $email . '<br/><br/>Message : ' . $message . '<br/>'; ?>
<br/>
</body>
</html>
I'll add layout/css later once I get the code working the way I would like.
any assistance will be most appreciated.
The "injection" code I am testing with is simply
"><script>alert('Broke');</script>
the sanitize works fine if I leave out the leading ">, even just using the "> alone messes up and page a little, I would like to know if there is a way to filter these just using options available in php.
Once I get input into this simple form working correctly I plan to use database functionality on the rest of the site so it is important to me that I get a good understanding of filtering for obvious reasons.
Thanks in Advance.
Aaron
Another Question, as you can see from the code I display an error if the email address is not valid according to the FILTER_VALIDATE_EMAIL, how would I go about doing this on the other fields (Name[text only], Telephone Number[10 digit telephone number] and Message[text with punctuation]) ?
I am also looking to add captcha script, a simple "random number [random calculation type +-X/] random number = answer" with the random numbers and calculation type displayed as an image, not sure where to start with this or if it would be too complicated for visitors.

You are doing some basic sanitising and validation but then proceeding to echo the raw (un-sanitised data) back to the client within the form.
<?php { echo $_POST['email']; } ?>
Change your value outputs to check for the sanitised values and output them appropriately.
<?php echo (isset($email) ? $email : ''); ?>

You are echoing the $_POST variables without sanitising them.
Wrap them in htmlspecialchars() like this:
echo htmlspecialchars($_POST['message']);

Related

Hide html when submit button clicked, echo results staying on same page, email form results EXAMPLE PROVIDED

I searched for a basic explanation and example on how to hide my html form "onsubmit" with basic php, while staying on the same page. I also needed to email the form results. I found bits here and there usually complicated and outside of my beginner abilities. So I am going to share a basic example of what I think is the easiest way to obtain this.
HTML Form with php:
<?php
session_start();
//if you require login start session first thing at top
?>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
</script>
</head>
<title>Example Form </title>
<?php
//my database connection is in insert.php
include_once 'insert.php';
//Set up email to receive the desired form results
$submit = $_POST['submit'];
$to = "youremail#yourdomain.com";
$email = "youremail#yourdomain.com";
$user = $_SESSION['yoursession']; #this is if require user login
$companyname = $_POST['companyname'];
$companyurl = $_POST['companyurl'];
$ipaddress = $_SERVER['REMOTE_ADDR']; #capture user's ip address
$subject = $companyname;
if(isset($submit) && !empty($companyname || $companyurl)){
$headers = 'From:'. $email . "\r\n"; // Sender's Email
//$headers .= 'Cc:'. $email . "\r\n"; // Carbon copy to Sender
$body = "
Company Name: $companyname \n\n Company URL: $companyurl \n\n User IP Address: $ipaddressadvertise
";
if(mail($to, $subject, $body, $headers)){
//What will show after submit button selected...
echo "Successfully submitted!" . "<br />";
echo "<br />" . "<strong>Company Name: </strong> " . " " . "$companyname" . "<br />" . "<strong>Company Website: </strong> " . " " . "$companyurl" . "<br />";
}else {
echo "Oops something went wrong. Try again or come back later. " . "<br />";
}
}
?>
<body>
<?php
//This is where you start to wrap what you want to hide onsubmit.
$submit = $_POST['submit'];
if(!isset($submit)){
//Do NOT put closing curly brace leave open and see below.
?>
<form id="form" name="form" action="" method="post" <?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>
<table border="0">
<tr>Company Name: <align = "center"><input type = "text" id = "companyname" name = "companyname" value = "" placeholder = "Required" required><br /><br />
<tr>Company Website: <align = "center"><input type = "text" id = "companyurl" name = "companyurl" value = "" placeholder = "Required" required><br /><br />
<input type="submit" name="submit" id="submit" onclick = "location.href='mailto:youremail#yourdomain.com';" value="Submit!">
<tr></tr><br /><br />
<tr></tr>
<tr></tr>
</form>
<?php
} //This is where you put your closing curly brace wrapping all of the information you want to hide when submit button is clicked.
?>
</body>
</html>
When the submit button is clicked the form should disappear, the message displays staying on the same page (without re-direct to another page) while emailing you the results.
NOTE: I tried this in the snippet and it didn't work. But I loaded it to a live site and it works perfectly without errors.
A basic structure can be something like that:
<?php
if (isset($_POST['submit'])) { // if submit - send email
$you = "YOUREMAIL";
$email = $_REQUEST['email'];
$subject = $_REQUEST['subject'];
$comment = $_REQUEST['comment'];
mail($you, $subject, $comment, "From:" . $email); //send email
echo "Thank you for contacting us!"; //Email response
}
else { // else display the form:
?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>">
<label for="email">Email:
<input name="email" id="email" type="email" />
</label>
<label for="subject">Subject:
<input name="subject" id="subject" type="text" />
</label>
<label for="comment">Comment:
<textarea name="comment" id="comment" rows="15" cols="40"></textarea>
</label>
<input type="submit" value="Submit" />
</form>
<?php } ?>

Receiving Spam from my Form Using PHPMailer

I am coming to stackoverflow for this because everything I search pretty much talks about email from a form using PHPMailer going to a users spam box. But, I need info on receiving spam from the form itself. I use it on a small, very light traffic real estate agents website. She gets spam from time to time and I don't know how to resolve it. PHPMailer seems to be the go to tool for sending email with PHP, so I figure spam/security is pretty well covered. I must be doing something wrong.... I am using class.phpmailer.php of course, and here is my code:
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = trim($_POST["name"]);
$email = trim($_POST["email"]);
$phone = trim($_POST["phone"]);
$message = trim($_POST["message"]);
if ($name == "" OR $email == "" OR $phone == "" OR $message == "") {
echo "You must specify a value for name, email address, phone, and 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 form submission has an error.";
exit;
}
require_once("phpmailer/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 . "Phone: " . $phone . "<br>";
$email_body = $email_body . "Message: " . $message;
$mail->SetFrom($email, $name);
$address = "email#domain.com";
$mail->AddAddress($address, "A Name Here");
$mail->Subject = "Message from " . $name . " on website contact form";
$mail->MsgHTML($email_body);
if(!$mail->Send()) {
echo "There was a problem sending the email: " . $mail->ErrorInfo;
exit;
}
header("Location: index.php?status=thanks");
exit;
}
The HTML is very simple:
<form id="form" name="form" method="post" action="contact-process.php">
<?php if (isset($_GET["status"]) AND $_GET["status"] == "thanks") { ?>
<p class="form-thanks">Thank you for contacting us. We'll be in touch with you very soon.</p>
<?php } ?>
<label>Name
<span class="small">First and Last</span>
</label>
<input type="text" name="name" id="name" />
<label>E-Mail
<span class="small">name#email.com</span>
</label>
<input type="text" name="email" id="email" />
<label>Phone Number
<span class="small">With area code</span>
</label>
<input type="text" name="phone" id="phone" />
<label>Message
<span class="small">How can we help you?</span>
</label>
<textarea cols="40" rows="8" name="message"></textarea>
<button type="submit">Submit</button>
<div class="spacer"></div>
</form>
A simple technique to avoid spam is to use something called a honey-pot, which is a text field which is not visible to normal users but a dumb spam-robot will probably enter something into that field.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// robot detection
$honeypot = trim($_POST["email"]);
if(!empty($honeypot)) {
echo "BAD ROBOT!";
exit;
}
$name = trim($_POST["name"]);
$email = trim($_POST["real_email"]);
$phone = trim($_POST["phone"]);
$message = trim($_POST["message"]);
// rest stays as is
In your HTML file you need to insert another "hidden" text field which is the honeypot:
<label>E-Mail
<span class="small">name#email.com</span>
</label>
<input type="text" name="email" style="display: none;">
<input type="text" name="email_real" id="email" />
Note how I changed the name of the actual, visible email text field to "email_real". It would be even better to avoid the word "email" completely in the real email field, since many robots are dumb.
The invisible honeypot input field should be called "email" though. Why? Because most robots are scanning for some standard input fields like "email", "address" etc. - so it's important to give the honeypot a common form field name.
Another neat trick is to swap some common field names, i.e swap the name for email and zip fields, so robots will fill in a numeric value for the email address and an email address for the zip code which will fail the validation.
It's not a 100% guarantee to kill all spam but it worked quite well for me without forcing the user to solve an annoying captcha...

How do I get my external send mail php file to check if the captcha is correct

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.

How to validate the captcha

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...

PHP Trying to add ability to send attachment to working contact us form

I have a friend who asked me to modify her website's contact form to request phone number and also the ability to add photo attachments. I've added the code necessary to request and send the phone number with the email, but adding the ability to attach photo files is beyond the current scope of my knowledge. Could someone take a look at the code and tell me how to add the ability to attach files to the message? All I'm trying to do is add this below the current message field, but it's proving to be more involved than I expected. Since everything I tried has broken the current form, I've removed my code attempts to add the attachment and I'm posting the code as it currently works. It's my hope someone with a better grasp of php can help us with this.
<?php
//set the level of error reporting
error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);
// Set-up these 3 parameters
$to = 'any#somewhere.net';
$subject = 'Question from The website';
$contact_submitted = 'Your message has been sent.';
function email_is_valid($email) {
return preg_match('/^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$/i',$email);
}
if (!email_is_valid($to)) {
echo '<p style="color: red;">You must set-up a valid (to) email address before this contact page will work.</p>';
}
if (isset($_POST['contact_submitted'])) {
$return = "\n\r";
$youremail = trim(htmlspecialchars($_POST['your_email']));
$yourname = stripslashes(strip_tags($_POST['your_name']));
$yourphone = trim(htmlspecialchars($_POST['your_phone']));
$yourmessage = stripslashes(strip_tags($_POST['your_message']));
$contact_name = "Name: ".$yourname;
$contact_email = "Email Address: ".$youremail;
$contact_phone = "Phone: ".$yourphone;
$message_text = "Message: ".$yourmessage;
$user_answer = trim(htmlspecialchars($_POST['user_answer']));
$answer = trim(htmlspecialchars($_POST['answer']));
$message = $contact_name . $return . $contact_email . $return . $contact_phone . $return . $return . $message_text;
$headers = "From: ".$youremail;
if (email_is_valid($youremail) && !eregi("\r",$youremail) && !eregi("\n",$youremail) && $yourname != "" && $yourphone != "" && $yourmessage != "" && substr(md5($user_answer),5,10) === $answer) {
mail($to,$subject,$message,$headers);
$yourname = '';
$youremail = '';
$yourphone = '';
$yourmessage = '';
echo '<p style="color: blue;">'.$contact_submitted.'</p>';
}
else echo '<p style="color: red;">Please enter your name, a valid email address, your message and the answer to the simple maths question before sending your message.</p>';
}
$number_1 = rand(1, 9);
$number_2 = rand(1, 9);
$answer = substr(md5($number_1+$number_2),5,10);
?>
<form id="contact" action="contact.php" method="post">
<div class="form_settings">
<p><span>Name:</span><input class="contact" type="text" name="your_name" value="<?php $yourname; ?>" /></p>
<p><span>Email Address:</span><input class="contact" type="text" name="your_email" value="<?php $youremail; ?>" /></p>
<p><span>Phone Number:</span><input class="contact" type="text" name="your_phone" value="<?php $yourphone; ?>" /></p>
<p><span>Message:</span><textarea class="contact textarea" rows="1" cols="50" name="your_message"><?php $yourmessage; ?></textarea></p>
<p style="line-height: 1.7em;">To help prevent spam, please enter the answer to this question:</p>
<p><span><?php echo $number_1; ?> + <?php echo $number_2; ?> = ?</span><input type="text" name="user_answer" /><input type="hidden" name="answer" value="<?php echo $answer; ?>" /></p>
<p style="padding-top: 15px"><span> </span><input class="submit" type="submit" name="contact_submitted" value="send" /></p>
</div>
</form>
If anyone can figure this out I'd be forever grateful.
First problem you're going to have is that you're not going to be able to upload any file without indicating the
enctype="multipart/form-data"
within the form tag.
The rest of the info, you could refer to this tutorial

Categories