I would like to send to my email the details of the users, but its not submitting the information to my mail box. How must I code it?
I tried to fix the local server, but its still failing to send, please help me on this. Thank you very much.
How can I fix the submit button?
if (!defined("PHP_EOL")) define("PHP_EOL", "\r\n");
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$select_price = $_POST['select_price'];
$select_service = $_POST['select_service'];
$subject = $_POST['subject'];
$comments = $_POST['comments'];
$verify = $_POST['verify'];
if(trim($first_name) == '') {
echo '<div class="error_message">Attention! You must enter your name.</div>';
exit();
} else if(trim($email) == '') {
echo '<div class="error_message">Attention! Please enter a valid email address.</div>';
exit();
} else if(!isEmail($email)) {
echo '<div class="error_message">Attention! You have enter an invalid e-mail address, try again.</div>';
exit();
}
if(trim($comments) == '') {
echo '<div class="error_message">Attention! Please enter your message.</div>';
exit();
}
if(get_magic_quotes_gpc()) {
$comments = stripslashes($comments);
}
I suppose you stripped the code, so the error on line 18 refers to
$subject = $_POST['subject'];
Double check that you do have an input named 'subject' on your page.
Related
When I click the submit button without filling the form, a new entry appears on database with the ID but the form keep validating and showing the user, this field is required but why the form is still submitting to the database?
Here is my code, kindly help, I am new in PHP and very tired of solving such problem.
<?php
include 'dbc.php';
// define variables and set to empty values
$name_error = $email_error = $phone_error = $url_error = $message_error = "";
$name = $email = $phone = $message = $url = $success = "";
//form is submitted with POST method
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (isset($_POST["name"])) {
$name_error = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$name_error = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$email_error = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$email_error = "Invalid email format";
}
}
if (empty($_POST["phone"])) {
$phone_error = "Phone is required";
} else {
$phone = test_input($_POST["phone"]);
// check if e-mail address is well-formed
}
if (empty($_POST["url"])) {
$url_error = "Website url is required";
} else {
$url = test_input($_POST["url"]);
// check if URL address syntax is valid (this regular expression also allows dashes in the URL)
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&##\/%?=~_|!:,.;]*[-a-z0-9+&##\/%=~_|]/i",$url)) {
$url_error = "Invalid URL";
}
}
if (empty($_POST["message"])) {
$message_error = "Message field is required";
} else {
$message = test_input($_POST["message"]);
}
if ($name_error == '' and $email_error == '' and $phone_error == '' and $url_error == '' and $message_error == ''){
$message = 'Hello Ladies';
unset($_POST['submit']);
foreach ($_POST as $key => $value){
$message .= "$key: $value\n";
}
$to = 'sample#email.com';
$subject = 'Contact Form Submit';
if (mail($to, $subject, $message)){
$success = "Message sent, thank you for contacting us!";
}
}
$query = "INSERT INTO clients(name,email,phone,url,message) ";
$query .= "VALUES('$name', '$email', '$phone', '$url', '$message') ";
$create_user = mysqli_query($mysqli, $query);
if (!$create_user) {
die("QUERY FAILED. " . mysqli_error($mysqli));
}
}
function test_input($data){
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
I hope I don't get downvote.
The only check actually being made before the query is run, is
if ($_SERVER["REQUEST_METHOD"] == "POST") {
which means that the only requirement for inserting values, is that the form is sent over POST, nothing else. This can be checked with a proper editor and seeing what brackets are wrapped around your query. You do some checks earlier in the code to validate and check the input, but this doesn't tell if the query should be run or not.
If you move the closing-bracket } of the following if-block
if ($name_error == '' and $email_error == '' and $phone_error == '' and $url_error == '' and $message_error == ''){
until after the query is performed, the query will only run if it passed all your checks. (place it after the following snippet)
if (!$create_user) {
die("QUERY FAILED. " . mysqli_error($mysqli));
}
In other remarks, your test_input() is rubbish (really) and you shouldn't use it. Parameterize your queries instead and filter the input with proper functions. There are validation filters and sanitation filters already implemented in PHP, you should use them if you need to.
You should prepare and bind the values of your queries using mysqli::prepare(), this will handle any issues dealing with quotes and protect your database against SQL injection.
References
mysqli::prepare()
How can I prevent SQL injection in PHP?
I'm currently building a very small 'contact' form for use on a personal site.
The form works, and each validation 'if' statement works individually, however, if for example I input a valid email address and phone number but leave the message blank, the email still sends and I get the success message.
My guess would be to include the small 'if' statements into the one checking whether my required fields are not empty, though i'm not sure how to do this correctly as it is nesting multiple 'if's into one.
Cheers
<?php
// Validation goes here
$errors = '';
$success = 'Success! Your message has been sent. You should receive a reply within 48 hours.';
$email = $_POST['email'];
$name = $_POST['thename'];
$comments = $_POST['comments'];
$number = $_POST['number'];
if(empty($name) || empty($email) || empty($comments)) {
$errors .= "Error: please input a name, email address and your message.";
} else {
$errors = '';
}
if (!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i", $email)) {
$errors .= "Error: Invalid email address";
} else {
$errors = '';
}
if (!preg_match("/^\(?0( *\d\)?){9,10}$/", $number)) {
$errors .= "Error: Invalid phone number";
} else {
$errors = '';
}
?>
<!-- Display red error box or green success box depending on which is true -->
<?php if(!empty($errors)): ?>
<div class="validationbox | errorsbox">
<?php echo $errors; ?>
</div>
<?php elseif(empty($errors)): ?>
<div class="validationbox | successbox">
<?php echo $success; ?>
</div>
<?php
$message = ''; // Blank message to start with so we can append to it.
// Construct the message
$message .= "
Name: {$_POST['thename']};
Email: {$_POST['email']};
Number: {$_POST['number']};
Enquiry-type: {$_POST['enquiry-options']};
Message: {$_POST['comments']};
";
// test#testdomain.com
$to = 'test-email-deleted-for-stackoverflow';
$subject = 'Message from Portfolio';
$from = $_POST['thename'];
// YourSite#domain.com
$fromEmail = 'test-email-deleted-for-stackoverflow';
$header = 'From: ' . $from . '<' . $fromEmail . '>';
mail($to,$subject,$message,$header);
?>
<?php endif; ?>
<?php endif; ?>
Your problem is that you are resetting $errors back to '' each time one of your validation conditions passes:
if(empty($name) || empty($email) || empty($comments)) {
$errors .= "Error: please input a name, email address and your message.";
} else {
$errors = '';
}
if (!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i", $email)) {
$errors .= "Error: Invalid email address";
} else {
$errors = '';
}
if (!preg_match("/^\(?0( *\d\)?){9,10}$/", $number)) {
$errors .= "Error: Invalid phone number";
} else {
$errors = '';
}
You shouldn't do that, just leave error messages to whatever it previously was. This way, when you get to the end, $errors will contain a string of all the error messages combined. Since there could be multiple messages, you may want to put a break a the end of each one:
if(empty($name) || empty($email) || empty($comments)) {
$errors .= "Error: please input a name, email address and your message.<br>";
}
if (!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i", $email)) {
$errors .= "Error: Invalid email address<br>";
}
if (!preg_match("/^\(?0( *\d\)?){9,10}$/", $number)) {
$errors .= "Error: Invalid phone number<br>";
}
In the case of email, you may want to only display the 'invalid email address' only when something was actually filled in, so you could also check to ensure there is something in there, before you determine if the format is valid or not:
if (!empty($email) && !preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i", $email)) {
Based on the information Supplied, i think you should use a complex if-elseif-else statement like so:
`if (condition) {
code to be executed if this condition is true;
} elseif (condition) {
code to be executed if this condition is true;
} else {
code to be executed if all conditions are false;
} `
in your particular case:
// Validation goes here
$errors = '';
$success = 'Success! Your message has been sent. You should receive a reply within 48 hours.';
$email = $_POST['email'];
$name = $_POST['thename'];
$comments = $_POST['comments'];
$number = $_POST['number'];
if(empty($name) || empty($email) || empty($comments)) {
$errors .= "Error: please input a name, email address and your message.";
} elseif(!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i", $email)) {
$errors = 'Error:invalid email';
}elseif(!preg_match("/^\(?0( *\d\)?){9,10}$/", $number){
$errors .= "Error: Invalid phone number";
} else {
//Do this on successful validation comes here
}
try below code it helps you.
<?php
// Validation goes here
$errors = '';
$success = 'Success! Your message has been sent. You should receive a reply within 48 hours.';
$email = $_POST['email'];
$name = $_POST['thename'];
$comments = $_POST['comments'];
$number = $_POST['number'];
if(empty($name) || empty($email) || empty($comments)) {
$errors .= "Error: please input a name, email address and your message.";
} else {
if (!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i", $email)) {
$errors .= "Error: Invalid email address";
} else {
$errors = '';
}
if (!preg_match("/^\(?0( *\d\)?){9,10}$/", $number)) {
$errors .= "Error: Invalid phone number";
} else {
$errors = '';
}
}
?>
I am new to PHP and currently getting back to HTML. I have made a form and have the data sent and validated by PHP but I am trying to send the email to myself only after the data had been validated and is correct. Currently if the page is loaded I think it send an email and it will send whenever I hit submit without the data being correct.
Here is where I validate the data:
<?php
//Set main variables for the data.
$fname = $lname = $email = $subject = $website = $likedsite = $findoption = $comments = "";
//Set the empty error variables.
$fnameErr = $lnameErr = $emailErr = $subjectErr = $commentsErr = $websiteErr = $findoptionErr = "";
//Check to see if the form was submitted.
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
//Check the 'First Name' field.
if (empty($_POST["fname"]))
{
$fnameErr = "First Name is Required.";
}
else
{
$fname = validate_info($_POST["fname"]);
}
//Check the 'Last Name' field.
if (empty($_POST["lname"]))
{
$lnameErr = "Last Name is Required.";
}
else
{
$lname = validate_info($_POST["lname"]);
}
//Check the 'E-Mail' field.
if (empty($_POST["email"]))
{
$emailErr = "E-Mail is Required.";
}
else
{
$email = validate_info($_POST["email"]);
//Check if valid email.
if (!filter_var($email, FILTER_VALIDATE_EMAIL))
{
$emailErr = "Invalid E-Mail Format.";
}
}
//Check the 'Subject' field.
if (empty($_POST["subject"]))
{
$subjectErr = "Subject is Required.";
}
else
{
$subject = validate_info($_POST["subject"]);
}
//Check the 'Website' field.
if (empty($_POST["siteurl"]))
{
$website = "";
}
else
{
$website = validate_info($_POST["siteurl"]);
//Check if valid URL.
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&##\/%?=~_|!:,.;]*[-a-z0-9+&##\/%=~_|]/i",$website))
{
$websiteErr = "Invalid URL.";
}
}
//Check the 'How Did You Find Us' options.
if (empty($_POST["howfind"]))
{
$findoptionErr = "Please Pick One.";
}
else
{
$findoption = validate_info($_POST["howfind"]);
}
//Check the comment box.
if (empty($_POST["questioncomments"]))
{
$commentsErr = "Questions/Comments are Required.";
}
else
{
$comments = validate_info($_POST["questioncomments"]);
}
//Pass any un-required data.
$likedsite = validate_info($_POST["likedsite"]);
}
function validate_info($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
Sorry its a little lengthy.
Here is where I try to send the email. I have tried two different attempts and both have the same result.
<?php
if (!empty($fnameErr) || !empty($lnameErr) || !empty($subjectErr) || !empty($emailErr) || !empty($commentErr) || !empty($websiteErr) || !empty($findoptionErr))
{
echo "Sent!!";
}else
{
echo"Not Sent!!";
}
//Make the message.
$message =
"
First Name: $fname.\n
Last Name: $lname.\n
Website: $website\n
Did They Like the Site? $likedsite.\n
How They Found Us. $findoption.\n
Question/Comments:\n
$comments.
";
$message = wordwrap($message, 70);
$headers = "From: $email";
mail("me#gmail.com", $subject, $message, $headers);
?>
Once again sorry for the length. Thanks in advance also sorry if this is a double question or not described enough I am also new to stack overflow.
Please try:
<?php
//Set main variables for the data.
$fname = $lname = $email = $subject = $website = $likedsite = $findoption = $comments = "";
//Set the empty error variables.
$fnameErr = $lnameErr = $emailErr = $subjectErr = $commentsErr = $websiteErr = $findoptionErr = "";
//Initialize variable used to identify form is valid OR not.
$formValid = true;
//Check to see if the form was submitted.
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
//Check the 'First Name' field.
if (empty($_POST["fname"]))
{
$formValid = false;//Form not validate
$fnameErr = "First Name is Required.";
}
else
{
$fname = validate_info($_POST["fname"]);
}
//Check the 'Last Name' field.
if (empty($_POST["lname"]))
{
$formValid = false;//Form not validate
$lnameErr = "Last Name is Required.";
}
else
{
$lname = validate_info($_POST["lname"]);
}
//Check the 'E-Mail' field.
if (empty($_POST["email"]))
{
$formValid = false;//Form not validate
$emailErr = "E-Mail is Required.";
}
else
{
$email = validate_info($_POST["email"]);
//Check if valid email.
if (!filter_var($email, FILTER_VALIDATE_EMAIL))
{
$formValid = false;//Form not validate
$emailErr = "Invalid E-Mail Format.";
}
}
//Check the 'Subject' field.
if (empty($_POST["subject"]))
{
$formValid = false;//Form not validate
$subjectErr = "Subject is Required.";
}
else
{
$subject = validate_info($_POST["subject"]);
}
//Check the 'Website' field.
if (empty($_POST["siteurl"]))
{
$website = "";
}
else
{
$website = validate_info($_POST["siteurl"]);
//Check if valid URL.
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&##\/%?=~_|!:,.;]*[-a-z0-9+&##\/%=~_|]/i",$website))
{
$formValid = false;//Form not validate
$websiteErr = "Invalid URL.";
}
}
//Check the 'How Did You Find Us' options.
if (empty($_POST["howfind"]))
{
$formValid = false;//Form not validate
$findoptionErr = "Please Pick One.";
}
else
{
$findoption = validate_info($_POST["howfind"]);
}
//Check the comment box.
if (empty($_POST["questioncomments"]))
{
$formValid = false;//Form not validate
$commentsErr = "Questions/Comments are Required.";
}
else
{
$comments = validate_info($_POST["questioncomments"]);
}
//Pass any un-required data.
$likedsite = validate_info($_POST["likedsite"]);
}
//If every variable value set, send mail OR display error...
if (!$formValid){
echo"Form not validate...";
}
else {
//Make the message.
$message =
"
First Name: $fname.\n
Last Name: $lname.\n
Website: $website\n
Did They Like the Site? $likedsite.\n
How They Found Us. $findoption.\n
Question/Comments:\n
$comments.
";
$message = wordwrap($message, 70);
$headers = "From: $email";
mail("me#gmail.com", $subject, $message, $headers);
if($sendMail){
echo "Mail Sent!!";
}
else {
echo "Mail Not Sent!!";
}
}
function validate_info($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
I edit my answer as per some change. Now this code only allow send mail if form required fields are not empty and all fields value are valid as per your validation.
Let me know if there is any concern.!
from what i was able to conceive, u are
trying to apply 'OR' in if condition- should be changed to AND i.e. change || to &&
you are checking for not empty error variables... which should be changed to verify if they all are empty or not.
if (empty($fnameErr) && empty($lnameErr) && empty($subjectErr) && empty($emailErr) && empty($commentErr) && empty($websiteErr) && empty($findoptionErr))
{
echo "sent";
}
Instead of writing lengthy conditions.
Assign all error messages to a single variable and append errors to it ($errorMsg). You can avoid lengthy if else ladder by doing this.
Change empty($_POST["email"]) to !isset($_POST["email"]) - In all statements.
Then update the condition to following,
<?php
if($errorMsg == ''){
//Make the message.
$message ="
First Name: ".$fname.".\n
Last Name: ".$lname."\n
Website: ".$website."\n
Did They Like the Site? ".$likedsite."\n
How They Found Us. ".$findoption."\n
Question/Comments:\n
".$comments." ";
$message = wordwrap($message, 70);
$headers = "From: $email";
mail("me#gmail.com", $subject, $message, $headers);
}else{
// Show $errorMsg
}
?>
Make it simple, I hope this helps.
I have a form, php validation, and send to email. My php validation works fine. My send to email works fine. When I use them both together, they work fine until I add header('Location: http://google.com'); exit(); I am using google.com for because I havent made my confirmation page yet. When I add this line to the php, that's when it goes straight to google.com when I go to my website. Can someone please help? I have been trying to figure out all of this validation and form to email for 2 straight days now, and I cannot figure it out. I know nothing about php. My code is below.
My php:
<?php
// define variables and set to empty values
$nameErr = $emailErr = $email2Err = $commentsErr = "";
$name = $email = $email2 = $comments = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if ( ! preg_match("/^[a-zA-Z ]*$/", $name)) {
$nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address syntax is valid
if ( ! preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["email2"])) {
$email2Err = "It is required to re-enter your email.";
} else {
$email2 = test_input($_POST["email2"]);
// check if e-mail address syntax is valid
if ( ! preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email2)) {
$email2Err = "Invalid email format";
}
}
if (empty($_POST["comments"])) {
$commentsErr = "A comment is required.";
} else {
$comments = test_input($_POST["comments"]);
if (preg_match("#^[a-zA-Z0-9 \.,\?_/'!£\$%&*()+=\r\n-]+$#", $comments)) {
// Everything ok. Do nothing and continue
} else {
$commentsErr = "Message is not in correct format.<br>You can use a-z A-Z 0-9 . , ? _ / ' ! £ $ % * () + = - Only";
}
}
if (isset($_POST['service'])) {
foreach ($_POST['service'] as $selectedService)
$selected[$selectedService] = "checked";
}
}
if (empty($errors)) {
$from = "From: Our Site!";
$to = "jasonriseden#yahoo.com";
$subject = "Mr Green Website | Comment from " . $name . "";
$message = "Message from " . $name . "
Email: " . $email . "
Comments: " . $comments . "";
mail($to, $subject, $message, $from);
header('Location: http://google.com');
exit();
}
?>
Please someone help me. I have no idea what is wrong.
Ok. I did what you told me Barmar. Not sure if I did it right or not. It solved one problem, but another was created.
I started over with the code that validates and sends the form data to my email. Now I just want to add header('Location: http://google.com '); exit(); ....and it work. Can you tell me what to do? I have no idea what php, so the more specific that you can be, the better.
Here is the php:
<?php
// define variables and set to empty values
$nameErr = $emailErr = $email2Err = $commentsErr = "";
$name = $email = $email2 = $comments = "";
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (empty($_POST["name"]))
{$nameErr = "Name is required";}
else
{$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name))
{
$nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["email"]))
{$emailErr = "Email is required";}
else
{$email = test_input($_POST["email"]);
// check if e-mail address syntax is valid
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$email))
{
$emailErr = "Invalid email format";
}
}
if (empty($_POST["email2"]))
{$email2Err = "It is required to re-enter your email.";}
else
{$email2 = test_input($_POST["email2"]);
// check if e-mail address syntax is valid
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$email2))
{
$email2Err = "Invalid email format";
}
}
if (empty($_POST["comments"]))
{$commentsErr = "A comment is required.";}
else
{$comments = test_input($_POST["comments"]);
if (preg_match("#^[a-zA-Z0-9 \.,\?_/'!£\$%&*()+=\r\n-]+$#", $comments)) {
// Everything ok. Do nothing and continue
} else {
$commentsErr = "Message is not in correct format.<br>You can use a-z A-Z 0-9 . , ? _ / ' ! £ $ % * () + = - Only";
}
}
if (isset($_POST['service']))
{
foreach ($_POST['service'] as $selectedService)
$selected[$selectedService] = "checked";
}
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if (empty($errors)) {
$from = "From: Our Site!"; //Site name
// Change this to your email address you want to form sent to
$to = "jasonriseden#yahoo.com";
$subject = "Mr Green Website | Comment from " . $name . "";
$message = "Message from " . $name . "
Email: " . $email . "
Comments: " . $comments . "";
mail($to,$subject,$message,$from);
}
?>
The problem is that there's no variable $errors. So if(empty($errors)) is always true, so it goes into the block that sends email and redirects. This happens even if the user hasn't submitted the form yet -- I'm assuming this code is part of the same script that displays the registration form after the code you posted.
You need to make two changes:
The code that sends the email and redirects should be moved inside the first if block, after all the validation checks.
Instead of if(empty($error)), it should check if($nameErr && $emailErr && $email2Err && $commentsErr). Or you should change the validation code to set $error whenever it's setting one of these other error message variables.
I know this isn't a direct answer to your question, but have a look into Exceptions. By having seperate functions for each validation and have them throw an exception when something is wrong, your code will be much cleaner and bugs will have much less room to pop up. Bonus points if you put all the validation functions in a class.
Example: (I renamed test_input() to sanitize_input(), because that's what it does)
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
try
{
$name = getValidatedName();
$email = getValidatedEmail();
// send email with $name and $email
}
catch (Exception $e)
{
echo '<div class="error">' . $e->getMessage() . '</div>';
}
}
function getValidatedName()
{
if (empty($_POST["name"]))
throw new Exception("Name is required");
$name = sanitize_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z ]*$/", $name))
throw new Exception("Only letters and white space allowed");
return $name;
}
function getValidatedEmail()
{
if (empty($_POST["email"]))
throw new Exception("Email is required");
$email = sanitize_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) // you don't have to reinvent the wheel ;)
throw new Exception("Invalid email format");
return $email;
}
I have two issues with a contact form I have created. I was previously hit hard by spam.
I am requiring that all fields be filled out before the form is processed, but what I have written isn't working: info goes into the database whether a person fills out all fields or not. ***fixed by using:
function validateForm()
{
var x=document.forms["validation"]["firstname"].value;
if (x==null || x=="")
{
alert("Please enter your first name");
return false;
}
for all fields and this one for email:
var x=document.forms["validation"]["email"].value;
var atpos=x.indexOf("#");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
{
alert("Please enter a valid email address");
return false;
}
Now, I need to get the captcha working or how to add to check if captcha is correct in same javascript? I think the error lies in this somehow?:
session_start();
if($_POST['submitted'] == "contactus")
if( $_SESSION['security_code'] == $_POST['security_code'] && !empty($_SESSION['security_code'] ) ) {
header("Location:http://www.berrieswebdesign.com/thankyou.php?message=thanks");
unset($_SESSION['security_code']);
} else {
// Insert your code for showing an error message here
echo "<div id='thankyoubox'>'Security breach! Security Breach! Ehem...Your security code was incorrect.'</div>";
}
ob_flush();
?>
And lastly, here is contactfunctions.php
<?php ob_start();//Required for the redirect to work?>
<?php
include_once("databasefunctions.php");
$contactsdbtable = "contacts";
function GetHeaders()
{
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
// Additional headers
$headers .= "To: {$firstname} <{$email}>" . "\r\n";
$headers .= 'From: My Website <info#mywebsite.com>' . "\r\n";
return $headers;
}
function ContactMessage($firstname, $lastname, $email, $message, $location)
{
global $contactsdbtable;
openDatabase();
$firstname = mysql_real_escape_string($firstname);
$lastname = mysql_real_escape_string($lastname);
$email = mysql_real_escape_string($email);
$message = mysql_real_escape_string($message);
$location = mysql_real_escape_string($location);
$result = QuickQuery("INSERT INTO {$contactsdbtable}(firstname, lastname, email, message, location)
VALUES('{$firstname}', '{$lastname}', '{$email}', '{$message}', '{$location}')");
if($result)
{
$headers = GetHeaders();
$message = "\"Thank you for contacting us at My Website. We will be answering your website inquiry post haste.\"<br />
<br />
<br />
Best Regards,<br />
<br />
Me
";
mail($email, "RE: Design Inquiry", $message, $headers);
mail("myemail#blahblah.com", "Website Inquiry", "{$firstname}, {$email}, has sent a web design inquiry", $headers);
}
}
?>
I appreciate any help I receive on this in advance. Also, since this is a lengthy post, would you guys mind listing which issue you are addressing, 1 or 2?
Thanks!
Ok try this:
<?php
$is_error = false;
if($_POST['submitted'] == "contactus")
{
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$message = $_POST['message'];
$location = $_POST['location'];
if(!$firstname || $firstname = ''){
$error = "Please enter your first name.";
$is_error = true;
} else if(!$lastname || $lastname= ''){
$error = "Please enter your last name.";
$is_error = true;
} else if(!$email || $email= ''){
$error = "Please enter a valid email.";
$is_error = true;
}else if(!$message || $message= ''){
$error = "Please enter your message.";
$is_error = true;
}else if(!$location || $location= ''){
$error = "Please tell us where you're from.";
$is_error = true;
}
if(($is_error === false) && ($_SESSION['security_code'] == $_POST['security_code']))
{
ContactMessage($firstname, $lastname, $email, $message, $location);
} else {
Error($error);
}
}
?>