I have designed a form which check validation when it is sent, I am using Swiftmailer and all of the validation works however I have a problem. When I return back to the contact form the errors are still there if they filled it out wrong so...
name is required!
email is required!
the errors only go when it passes validation.
How do I refresh the page when the user leaves and comes back to a fresh form?
Contact form:
<?php
session_start();
?>
<!doctype html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8" />
<title>Send a message</title>
</head>
<body>
<div class="container">
<div <?php if(isset($_SESSION['form_message'])) { echo 'style="color: green"'; } elseif (isset($_SESSION['form_errors'])) { echo 'style="color: red"'; } ?>>
<?php
if(isset($_SESSION['form_message']))
{
echo $_SESSION['form_message'];
unset($_SESSION['form_data']);
}
elseif(isset($_SESSION['form_errors']))
{
echo '<b>You have the following errors:</b>';
echo "<br>";
foreach($_SESSION['form_errors'] as $display_err) {
echo $display_err . "<br>";
}
}
?>
</div>
<form name="contact" method="post" action="swift_mail.php">
<div>
<label for="name">Full name</label><br />
<input type="text" name="name" id="name" value="<?php if(isset($_SESSION['form_data'])) { echo $_SESSION['form_data']['name'] ; } ?>" />
</div>
<div>
<label for="email">Email Address</label><br />
<input type="text" name="email" id="email" value="<?php if(isset($_SESSION['form_data'])) { echo $_SESSION['form_data']['email'] ; } ?>" />
</div>
<div>
<label for="comment">Comment</label><br />
<textarea name="comment" id="comment"><?php if(isset($_SESSION['form_data'])) { echo $_SESSION['form_data']['comment'] ; } ?></textarea>
<input type="submit" value="submit" name="submit_msg"/>
</div>
</form>
</div>
</body>
</html>
</code>
swift
<?php
session_start();
require_once 'Swift-5.0.3/lib/swift_required.php';
require 'vendor/autoload.php';
if(isset($_POST['submit_msg'])) {
/*
Validate data before it is posted
*/
$rule_set = array (
'name' => array(
'required'
),
'email' => array(
'required'
),
'comment' => array(
'required'
)
);
/*
Checking Validation
*/
$validation_result = SimpleValidator\Validator::validate($_POST, $rule_set);
if ($validation_result->isSuccess() == true ) {
/*
Contact Form Information
*/
$name = $_POST['name'];
$email = $_POST['email'];
$comment = $_POST['comment'];
// Main Point of contact
$email_address = 'ben#bubbledesign.co.uk';
// Composed Message
$body_msg = "Name: " . $name . "<br>" . "Comments: " .$comment;
/*
Swift Mail Transport
*/
$transport = Swift_MailTransport::newInstance();
$mail = Swift_Mailer::newInstance($transport);
/*
Create the Swift Message
*/
$message = Swift_Message::newInstance('Subject line')
->setFrom($email)
->setTo($email_address)
->setBody($body_msg, "text/html");
/*
Send Swift Message
*/
$result = $mail->send($message);
$_SESSION['form_message'] = "Thank you for your message someone will be in touch soon.";
unset($_SESSION['form_errors']);
unset($_SESSION['form_data']);
header('location: contact-form.php');
} else {
$_SESSION['form_data'] = $_POST;
$_SESSION['form_errors'] = $validation_result->getErrors();
header('Location: contact-form.php');
}
}
?>
Related
I was following a tutorial and completed this contact form. It works fine, but I want to display a different message in each of the field instead of using a one box. I tried to move
<?php if($msg != ''): ?>
<div class="alert <?php echo $msgClass; ?>"><?php echo $msg;?></div>
<?php endif; ?>
underneath the input field and that worked great as far as displaying in that spot, but it just shows the same message all at once. It does not show different message separately. How would I approach this from here?
body {
font-size:10px;
font-family:sans-serif, "Open-sans";
margin:0;
padding:0;
box-sizing:border-box;
letter-spacing:0.1rem;
}
.navbar {
background:#333;
width:100%;
}
.container {
max-width:1100px;
margin:auto;
}
.navbar-header {
display: flex;
flex-flow: row wrap;
justify-content: flex-start;
}
.navbar-brand {
font-size:1.5rem;
padding:1rem;
color:#fff;
text-decoration:none;
}
form {
font-size:1.3rem;
}
.form-group {
display:flex;
flex-direction: column;
margin:1.5rem;
}
label {
color:#333;
margin-bottom:0.7rem;
}
input, textarea {
max-width:100%;
border:0.5px solid darkslategray;
padding:1.3rem;
font-size:1.5rem;
}
button {
background:rgb(67, 130, 211);
color:#fff;
font-size:1.2rem;
padding:1rem;
margin:1.5rem;
border:none;
}
.alert {
margin:1.5rem;
padding:1.5rem;
font-size:1.5rem;
color:#fff;
}
.alert-danger {
background-color:rgb(219, 54, 48);
}
.alert-success {
background-color:rgb(28, 160, 39);
}
<?php
// Message Vars
$msg = '';
$msgClass = '';
// Check for submit
if(filter_has_var(INPUT_POST,'submit')){
// Get Form Data
$name = htmlspecialchars($_POST['name']);
$email = htmlspecialchars($_POST['email']);
$message = htmlspecialchars($_POST['message']);
// Check Required Fields
if(!empty($email) && !empty($name) && !empty($message)){
// Passed
// Check Email
if(filter_var($email, FILTER_VALIDATE_EMAIL) === false ){
// Failed
$msg = 'Please use a valid email';
$msgClass = 'alert-danger';
} else {
// Passed
$toEmail = 'johnDoe#gmail.com';
$subject = 'Contact Request From '.$name;
$body = '<h2>Contact Request</h2>
<h4>Name</h4><p>' .$name. '</p>
<h4>Email</h4><p>' .$email. '</p>
<h4>Message</h4><p>' .$message.'</p>
';
// Email Headers
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-Type:text/html;charaset=UTF-8" . "\r\n";
// Additional Headers
$headers .= "From: " .$name. "<".$email.">". "\r\n";
if(mail($toEmail, $subject, $body, $headers)){
// Email Sent
$msg = "Your email has been sent";
$msgClass = 'alert-success';
} else {
// Failed
$msg = "Your email was not sent";
$msgClass = 'alert-danger';
}
}
} else {
// Failed
$msg = 'Please fill in all fields';
$msgClass = 'alert-danger';
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<title>Contact US</title>
</head>
<body>
<nav class="navbar">
<div class="container">
<div class="navbar-header">
My Website
</div>
</div>
</nav>
<div class="container">
<?php if($msg != ''): ?>
<div class="alert <?php echo $msgClass; ?>"><?php echo $msg;?></div>
<?php endif; ?>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
<div class="form-group">
<label for="name">Name</label>
<input type="text" name="name" class="form-control" value="<?php echo isset($_POST['name']) ? $name : ''; ?>">
</div>
<div class="form-group">
<label for="name">Email</label>
<input type="text" name="email" class="form-control" value="<?php echo isset($_POST['email']) ? $email : ''; ?>">
</div>
<div class="form-group">
<label for="name">Message</label>
<textarea name="message" class="form-control"><?php echo isset($_POST['message']) ? $message : ''; ?></textarea>
</div>
<button type="submit" name="submit" class="btn btn-primary">
Submit</button>
</form>
</div>
</body>
</html>
This is my current form.
I want to make it look like this one.
You can use the $msg variable as an array, instead of a string, to hold errors for specific fields.
<?php
$msg = [];
if(filter_has_var(INPUT_POST,'submit')){
//...
// Check Required Fields
if(!empty($email) && !empty($name) && !empty($message)){
if(filter_var($email, FILTER_VALIDATE_EMAIL) === false ){
$msg['email'] = [
'msg' => 'Please use a valid email'
'class' => 'alert-danger'
];
} else {
//...
if(mail($toEmail, $subject, $body, $headers)){
// Email Sent
$msg['default'] = [
'msg' => 'Your email has been sent'
'class' => 'alert-success'
];
} else {
// Failed
$msg['default'] = [
'msg' => 'Your email was not sent'
'class' => 'alert-danger'
];
}
}
} else {
// Failed
$msg['default'] = [
'msg' => 'Please fill in all fields'
'class' => 'alert-danger'
];
}
}
?>
And now in the HTML, you can check if the specific error or message exist and you display it at the right place; default messages at the top and email error under the email input:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<title>Contact US</title>
</head>
<body>
<nav class="navbar">
<div class="container">
<div class="navbar-header">
My Website
</div>
</div>
</nav>
<div class="container">
<!-- HERE -->
<?php if(isset($msg['default'])): ?>
<div class="alert <?php echo $msg['default']['class']; ?>"><?php echo $msg['default']['msg']?></div>
<?php endif; ?>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
<!-- ... -->
<div class="form-group">
<label for="name">Email</label>
<input type="text" name="email" class="form-control" value="<?php echo isset($_POST['email']) ? $email : ''; ?>">
<!-- AND HERE -->
<?php if(isset($msg['email'])): ?>
<div class="alert <?php echo $msg['email']['class']; ?>"><?php echo $msg['email']['msg']?></div>
<?php endif; ?>
</div>
<!-- ... -->
</form>
</div>
</body>
</html>
And you can actually do the same for any other input you want too.
You can store your validation warnings in an array type variable as opposed to a string.
For example, this line:
$msg = 'Please use a valid email';
You could instead do this:
$msg['email'] = 'Please use a valid email';
Also I think you want to verify if each of the required fields is present with its own individual if check, not all of them together, for example:
if(!empty($email) && !empty($name) && !empty($message)){
You can implement as:
if (empty($email) || filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
$msg['email'] = 'Please use a valid email';
}
if (empty($name)) {
$msg['name'] = 'Please enter a name';
}
if (empty($message)) {
$msg['message'] = 'Please enter a message';
}
Then in your HTML section, below each of the relevant input fields, you can add:
<div class="form-group">
<label for="name">Name</label>
<input type="text" name="name" class="form-control" value="<?php echo isset($_POST['name']) ? $name : ''; ?>">
<?php if(isset($msg['name'])): ?>
<p> <?php echo $msg['name']; ?>
<?php endif; ?>
</div>
However, in general I have to say this a very oldschool way of using PHP, where you would mix your logic code with your display code.
When you get the hang of it, perhaps you would like to study how Laravel, Symfony, or even CodeIgniter work, where you can use what known as MVC to separate your display from your logic.
As well, you can eventually use a templating engine like Blade or similar to echo out your variables.
I have the assignment below and I'm stuck at Step # 3 with the code file named inputforassignment2.php --basically, I am trying to append (add) rows to the existing data (songs.csv file) via that file with input fields. I tried to fix that code (which i obtained from a website, see sample source code far below, but it's returning errors or creates blank and numerical data in rows for each input.
Assignment: Create a simple PHP page that reads/writes to and from a .CSV file
The .CSV file should contain a list of your favorite items (for
example: songs, games, books, authors, etc,..). Each record in your
file should contain at least 3 attributes for your favorite item.
Also, it should have at least 7 records. --this part is done
The PHP should read the file and display the records in a TABLE with
the corresponding headers for each attribute of your favorite item.
--this part is done
Also, in the page should be a link (<< I did that part) that takes to another page where a new record can be added to the file. Then the list should display all previous records plus the new one. (<< where I am stuck)
-all my current source files:
song.csv
Song Title,Artist,Track Year
FLY,Sik-K,2017
Doverstreet,RIN,2017
Half Moon,Dean,2016
Blacklist,Loopy,2017
N/A,JooYoung,2018
Heyahe,ONE,2017
ADY,Sik-K,2017
assignment2.php how this php code displays song.csv
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Assignment 2</title>
</head>
<?php
echo "<table border=1> ";
$f = fopen("song.csv", "r"); //open a file in read mode
while (($line = fgetcsv($f)) !== false) { //read the each line of csv file
echo "<tr>"; //for printing in the table
foreach ($line as $cell) { //each data of line
echo "<td>" . htmlspecialchars($cell) . "</td>"; //print in the table
}
echo "</tr> ";
}
fclose($f); //close file
echo " </table>";
?>
Click here to add more songs!
<body>
</body>
</html>
inputformassignment2.php
<?php
//index.php
$error = '';
$name = '';
$email = '';
$subject = '';
function clean_text($string)
{
$string = trim($string);
$string = stripslashes($string);
$string = htmlspecialchars($string);
return $string;
}
if(isset($_POST["submit"]))
{
if(empty($_POST["name"]))
{
$error .= '<p><label class="text-danger">Please Enter your Name</label></p>';
}
else
{
$name = clean_text($_POST["name"]);
if(!preg_match("/^[a-zA-Z ]*$/",$name))
{
$error .= '<p><label class="text-danger">Only letters and white space allowed</label></p>';
}
}
if(empty($_POST["subject"]))
{
$error .= '<p><label class="text-danger">Subject is required</label></p>';
}
else
{
$subject = clean_text($_POST["subject"]);
}
if($error == '')
{
$file_open = fopen("contact_data.csv", "a");
$no_rows = count(file("contact_data.csv"));
if($no_rows > 1)
{
$no_rows = ($no_rows - 1) + 1;
}
$form_data = array(
'sr_no' => $no_rows,
'name' => $name,
'email' => $email,
'subject' => $subject,
);
fputcsv($file_open, $form_data);
$error = '<label class="text-success">Thank you for contacting us</label>';
$name = '';
$email = '';
$subject = '';
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Add A New Song</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<br />
<div class="container">
<h2 align="center">Add A New Song</h2>
<br />
<div class="col-md-6" style="margin:0 auto; float:none;">
<form method="post">
<h3 align="center">Type below:</h3>
<br />
<?php echo $error; ?>
<div class="form-group">
<label>Song Title</label>
<input type="text" name="name" placeholder="Type your song title" class="form-control" value="<?php echo $name; ?>" />
</div>
<div class="form-group">
<label>Song Artist</label>
<input type="text" name="email" class="form-control" placeholder="Type the song artist here" value="<?php echo $email; ?>" />
</div>
<div class="form-group">
<label>Track Year</label>
<input type="text" name="subject" class="form-control" placeholder="Put the song's track year here" value="<?php echo $subject; ?>" />
</div>
<div class="form-group" align="center">
<input type="submit" name="submit" class="btn btn-info" value="Submit" />
</div>
</form>
</div>
</div>
</body>
</html>
sample source code obtained from website:
<?php
//index.php
$error = '';
$name = '';
$email = '';
$subject = '';
$message = '';
function clean_text($string)
{
$string = trim($string);
$string = stripslashes($string);
$string = htmlspecialchars($string);
return $string;
}
if(isset($_POST["submit"]))
{
if(empty($_POST["name"]))
{
$error .= '<p><label class="text-danger">Please Enter your Name</label></p>';
}
else
{
$name = clean_text($_POST["name"]);
if(!preg_match("/^[a-zA-Z ]*$/",$name))
{
$error .= '<p><label class="text-danger">Only letters and white space allowed</label></p>';
}
}
if(empty($_POST["email"]))
{
$error .= '<p><label class="text-danger">Please Enter your Email</label></p>';
}
else
{
$email = clean_text($_POST["email"]);
if(!filter_var($email, FILTER_VALIDATE_EMAIL))
{
$error .= '<p><label class="text-danger">Invalid email format</label></p>';
}
}
if(empty($_POST["subject"]))
{
$error .= '<p><label class="text-danger">Subject is required</label></p>';
}
else
{
$subject = clean_text($_POST["subject"]);
}
if(empty($_POST["message"]))
{
$error .= '<p><label class="text-danger">Message is required</label></p>';
}
else
{
$message = clean_text($_POST["message"]);
}
if($error == '')
{
$file_open = fopen("contact_data.csv", "a");
$no_rows = count(file("contact_data.csv"));
if($no_rows > 1)
{
$no_rows = ($no_rows - 1) + 1;
}
$form_data = array(
'sr_no' => $no_rows,
'name' => $name,
'email' => $email,
'subject' => $subject,
'message' => $message
);
fputcsv($file_open, $form_data);
$error = '<label class="text-success">Thank you for contacting us</label>';
$name = '';
$email = '';
$subject = '';
$message = '';
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>How to Store Form data in CSV File using PHP</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<br />
<div class="container">
<h2 align="center">How to Store Form data in CSV File using PHP</h2>
<br />
<div class="col-md-6" style="margin:0 auto; float:none;">
<form method="post">
<h3 align="center">Contact Form</h3>
<br />
<?php echo $error; ?>
<div class="form-group">
<label>Enter Name</label>
<input type="text" name="name" placeholder="Enter Name" class="form-control" value="<?php echo $name; ?>" />
</div>
<div class="form-group">
<label>Enter Email</label>
<input type="text" name="email" class="form-control" placeholder="Enter Email" value="<?php echo $email; ?>" />
</div>
<div class="form-group">
<label>Enter Subject</label>
<input type="text" name="subject" class="form-control" placeholder="Enter Subject" value="<?php echo $subject; ?>" />
</div>
<div class="form-group">
<label>Enter Message</label>
<textarea name="message" class="form-control" placeholder="Enter Message"><?php echo $message; ?></textarea>
</div>
<div class="form-group" align="center">
<input type="submit" name="submit" class="btn btn-info" value="Submit" />
</div>
</form>
</div>
</div>
</body>
</html>
I am following this tutorial on youtube on how to make a contact form (https://www.youtube.com/watch?v=9KS2QuFXIs8) and im at a part where some of my php code will not run because of ...
<?php else: ?>
<p>Thank you for your Message!</p>
<?php endif; ?>
also
<?php if($form_complete === FALSE): ?>
The rest of the code below that uses php works so im sure its not the server but maybe the fact the above code has a colon. Here's the rest of the code.
<?php
// Set email variables
$email_to = 'guomonster#gmail.com';
$email_subject = 'Form submission';
// Set required fields
$required_fields = array('fullname','email','comment');
// set error messages
$error_messages = array(
'fullname' => 'Please enter a Name to proceed.',
'email' => 'Please enter a valid Email Address to continue.',
'comment' => 'Please enter your Message to continue.'
);
// Set form status
$form_complete = FALSE;
// configure validation array
$validation = array();
// check form submittal
if(!empty($_POST)) {
// Sanitise POST array
foreach($_POST as $key => $value) $_POST[$key] = remove_email_injection(trim($value));
// Loop into required fields and make sure they match our needs
foreach($required_fields as $field) {
// the field has been submitted?
if(!array_key_exists($field, $_POST)) array_push($validation, $field);
// check there is information in the field?
if($_POST[$field] == '') array_push($validation, $field);
// validate the email address supplied
if($field == 'email') if(!validate_email_address($_POST[$field])) array_push($validation, $field);
}
// basic validation result
if(count($validation) == 0) {
// Prepare our content string
$email_content = 'New Website Comment: ' . "\n\n";
// simple email content
foreach($_POST as $key => $value) {
if($key != 'submit') $email_content .= $key . ': ' . $value . "\n";
}
// if validation passed ok then send the email
mail($email_to, $email_subject, $email_content);
// Update form switch
$form_complete = TRUE;
}
}
function validate_email_address($email = FALSE) {
return (preg_match('/^[^#\s]+#([-a-z0-9]+\.)+[a-z]{2,}$/i', $email))? TRUE : FALSE;
}
function remove_email_injection($field = FALSE) {
return (str_ireplace(array("\r", "\n", "%0a", "%0d", "Content-Type:", "bcc:","to:","cc:"), '', $field));
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Contact Form</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link href="css/contactform.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
var nameError = '<?php echo $error_messages['fullname']; ?>';
var emailError = '<?php echo $error_messages['email']; ?>';
var commentError = '<?php echo $error_messages['comment']; ?>';
</script>
</head>
<body>
<div id="formWrap">
<div id="form">
<?php if($form_complete === FALSE); ?>
<form>
<div class="row">
<div class="label">
Your Name
</div>
<div class="input">
<input type="text" name="fullname" id="fullname" class="detail" value="<?php echo isset($_POST['fullname'])? $_POST['fullname'] : ''; ?>" />
<?php if(in_array('fullname', $validation)): ?><span class="error"><?php echo $error_messages['fullname']; ?></span><?php endif; ?>
</div>
<div class="context">
e.g. John Smith
</div>
</div>
<div class="row">
<div class="label">
Your Email
</div>
<div class="input">
<input type="text" name="email" id="email" class="detail" value="<?php echo isset($_POST['email'])? $_POST['email'] : ''; ?>" />
<?php if(in_array('email', $validation)): ?><span class="error"><?php echo $error_messages['email']; ?></span><?php endif; ?>
</div>
<div class="context">
We will not share your email.
</div>
</div>
<div class="row">
<div class="label">
Your Message
</div>
<div class="input">
<textarea name="comment" id="comment" class="mess"><?php echo isset($_POST['comment'])? $_POST['comment'] : ''; ?></textarea>
<?php if(in_array('comment', $validation)): ?><span class="error"><?php echo $error_messages['comment']; ?></span><?php endif; ?>
</div>
</div>
<div class="submit">
<input type="submit" id="submit" name="submit" value="Send Message">
</form>
</div>
<?php else: ?>
<p>Thank you for your Message!</p>
<?php endif; ?>
</div>
</div>
</body>
</html>
In PHP You should use Brackets for conditional codeblocks.
<?php if ($form_complete === FALSE) { ?>
<p>if-branch</p>
<?php } else { ?>
<p>Thank you for your Message!</p>
<?php } ?>
But using PHP code inside html can be very confusing. Try the following:
<?php
if ($form_complete === FALSE) {
// do something
} else {
echo '<p>Thank you for your Message!</p>'
}
?>
I am working with on a contact form similar to the one shown by Dreamweaver Tutorial.
I have a followed his instructions fairly well except when it came to the CSS. However, after linking the form up to my site, I keep getting the validation error:
"Please enter your message to continue"
This occurs even after I have entered a message. I have gone through his 2-part series twice and have not been able to find an answer.
My code:
<?php
// Set email variables
$email_to = 'Matt#matthewbrianhawn.com';
$email_subject = 'Someone Contacted You on Your Site';
// Set required fields
$required_fields = array('name','email','comment');
// set error messages
$error_messages = array(
'name' => 'Please enter a Name to proceed.',
'email' => 'Please enter a valid Email Address to continue.',
'comment' => 'Please enter your Message to continue.'
);
// Set form status
$form_complete = FALSE;
// configure validation array
$validation = array();
// check form submittal
if(!empty($_POST)) {
// Sanitise POST array
foreach($_POST as $key => $value) $_POST[$key] = remove_email_injection(trim($value));
// Loop into required fields and make sure they match our needs
foreach($required_fields as $field) {
// the field has been submitted?
if(!array_key_exists($field, $_POST)) array_push($validation, $field);
// check there is information in the field?
if($_POST[$field] == '') array_push($validation, $field);
// validate the email address supplied
if($field == 'email') if(!validate_email_address($_POST[$field])) array_push($validation, $field);
}
// basic validation result
if(count($validation) == 0) {
// Prepare our content string
$email_content = 'New Website Comment: ' . "\n\n";
// simple email content
foreach($_POST as $key => $value) {
if($key != 'submit') $email_content .= $key . ': ' . $value . "\n";
}
// if validation passed ok then send the email
mail($email_to, $email_subject, $email_content);
// Update form switch
$form_complete = TRUE;
}
}
function validate_email_address($email = FALSE) {
return (preg_match('/^[^#\s]+#([-a-z0-9]+\.)+[a-z]{2,}$/i', $email))? TRUE : FALSE;
}
function remove_email_injection($field = FALSE) {
return (str_ireplace(array("\r", "\n", "%0a", "%0d", "Content-Type:", "bcc:","to:","cc:"), '', $field));
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<!-- Contact Form Designed by James Brand # dreamweavertutorial.co.uk -->
<!-- Covered under creative commons license - http://dreamweavertutorial.co.uk/permissions/contact-form-permissions.htm -->
<title>Contact Form</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link href="contact/css/style.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
var nameError = '<?php echo $error_messages['name']; ?>';
var emailError = '<?php echo $error_messages['email']; ?>';
var commentError = '<?php echo $error_messages['comment']; ?>';
</script>
</head>
<body>
<div id="form-main">
<div id="form-div">
<?php if($form_complete === FALSE): ?>
<form class="form" id="form1" action="index.php" method="post">
<p class="name">
<input name="name" type="text" class="validate[required,custom[onlyLetter],length[0,100]] feedback-input" placeholder="Name" id="name" value="<?php echo isset($_POST['name'])? $_POST['name'] : ''; ?>" />
<?php if(in_array('name', $validation)): ?><span class="error"><?php echo $error_messages['name']; ?></span><?php endif; ?>
</p>
<p class="email">
<input name="email" type="text" class="validate[required,custom[email]] feedback-input" id="email" placeholder="Email" value="<?php echo isset($_POST['email'])? $_POST['email'] : ''; ?>" /><?php if(in_array('email', $validation)): ?><span class="error"><?php echo $error_messages['email']; ?></span><?php endif; ?>
</p>
<p class="text">
<textarea name="text" class="feedback-input" id="comment" placeholder="Comment" ><?php echo isset($_POST['comment'])? $_POST['comment'] : ''; ?></textarea>
<?php if(in_array('comment', $validation)): ?><span class="error"><?php echo $error_messages['comment']; ?></span><?php endif; ?>
</p>
<div class="submit">
<input type="submit" value="SEND" id="button-blue" name="submit"/>
<div class="ease"></div>
</div>
</form>
<?php else: ?>
<div class="thanks_message">
<p>Thank you for your Message!</p>
</div>
<?php endif; ?>
</div>
</body>
</html>
In your text field definition for comment you have
textarea name="text" class="feedback-input" id="comment" placeholder="Comment"
id change it to
textarea name="comment" class="feedback-input" id="comment" placeholder="Comment"
Thats why it sees it as empty because currently its called "text" not "comment"
It's simply because the key 'comment' doesn't exist in your $_POST variable.
For instance the keys of your variable $_POST are the name of your input form.
Just try to replace 'comment' by the name of your field ('text') in your variable $error_messages
I have used this contact form before, I just changed out the information. For some reason now though it won't send. I gone over the html and php but I can't see the error. The only difference is that now I'm using godaddy, but other than that I'm not seeing what the error is. HELP!
HTML:
<div id="MainForm">
<form method="post" action="ContactForm-Handler.php" name="Contact Form" target="_parent" id="ContactForm" title="Contact Form">
<h1>Contact Form</h1>
<p>Please fill out information below.</p>
<p>
<label for="Name">Name:</label>
<input type="text" name="Name" id="Name" /><br /><br />
<label for="Email">Email: </label>
<input type="text" name="Email" id="Email" /><br /><br />
<label for="QuestionType">Regarding: </label>
<select name="QuestionType" id="QuestionType">
<option value="Products">Products</option>
<option value="Pricing">Pricing</option>
<option value="Terms">Terms</option>
<option value="Other Information">Other</option>
</select>
<br /><br />
<label for="MessageBox">Message: </label>
<Br /><br />
<textarea name="MessageBox" cols="50" rows="10">Enter Question/Message Here</textarea>
</p>
<p><input name="Send" type="submit" id="Send" onmouseup="ThankYou.html" value="Submit" />
</p>
</form>
</div>
PHP:
<?php
$errors = '';
$myemail = 'myemail#gmail.com';
$name = $_POST['Name'];
$email = $_POST['Email'];
$message = $_POST['MessageBox'];
$question = $_POST['QuestionType'];
if(!empty($_POST['Products'])) {
foreach($_POST['Products'] as $products) {
echo $check;
}
}
if(!empty($_POST['Pricing'])) {
foreach($_POST['Pricing'] as $pricing) {
echo $check;
}
}
if(!empty($_POST['Terms'])) {
foreach($_POST['Terms'] as $terms) {
echo $check;
}
}
if(!empty($_POST['Other Information'])) {
foreach($_POST['Other Information'] as $other) {
echo $check;
}
}
if( empty($errors))
{
$to = $myemail;
$email_subject = "Contact Form Submission";
$email_body = "$name needs some information regarding $question \n \n".
"$message";
$headers = "From: $myemail\n";
$headers .= "Reply-To: $email";
mail($to,$email_subject,$email_body,$headers);
//redirect to the 'thank you' page
header('Location: ThankYou.html');
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>qp Contact Form</title>
</head>
<body>
<!-- This page is displayed only if there is some error -->
<?php
echo nl2br($errors);
?>
</body>
</html>
if(!empty($_POST['Products'])) {
foreach($_POST['Products'] as $products) {
echo $check;
}
}
if(!empty($_POST['Pricing'])) {
foreach($_POST['Pricing'] as $pricing) {
echo $check;
}
}
if(!empty($_POST['Terms'])) {
foreach($_POST['Terms'] as $terms) {
echo $check;
}
}
if(!empty($_POST['Other Information'])) {
foreach($_POST['Other Information'] as $other) {
echo $check;
}
}
Remove this part of your code because here you're checking with the value of the <option> tag.
You should use name of your <select> box instead.
like this :
//we use name attributes. not value attributes. otherwise $_POST will have Undefined Index error.
if(!empty($_POST['QuestionType'])){
foreach($_POST['QuestionType'] as $QuestionType){
echo $check;
}
}
And yeah, use <?php error_reporting(E_ALL); ?> at the top of your php page to enable php to show you errors.