I'm kinda new in PHP and I've created a form that should validate data and submit an error if any field is blank or incorrect. It doesn't tho. Even if email is wrong or any field is empty and the errors are shown it still sends an email. And the headers are not showing in the message. The only case when the errors are shown and the mail isn't send is the case when all fields are empty. Here's the code:
<?php
$NameErr = $EmailErr = $SubErr = $MessErr = "";
$Name = $Email = $Subject = $Message = "";
$header = "From: " . $Email . "Name: " . $Name . "\r\n";
$header .= "Content-Type: text/plain";
$To = "xxx#gmail.com";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["Name"])) {
$NameErr = "Name is required";
} else {
$Name = test_input($_POST["Name"]);
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"]);
if (!filter_var($Email, FILTER_VALIDATE_EMAIL)) {
$EmailErr = "Invalid email format";
}
}
if (empty($_POST["Subject"])) {
$SubErr = "Subject is required";
} else {
$Subject = test_input($_POST["Subject"]);
}
if (empty($_POST["Message"])) {
$MessErr = "Message is required";
} else {
$Message = test_input($_POST["Message"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
<p><input class="w3-input w3-padding-16" type="text" placeholder="Name" name="Name"></p>
<span class="error"> <?php echo $NameErr; ?></span>
<p><input class="w3-input w3-padding-16" type="text" placeholder="Email" name="Email"></p>
<span class="error"> <?php echo $EmailErr; ?></span>
<p><input class="w3-input w3-padding-16" type="text" placeholder="Subject" name="Subject"></p>
<span class="error"> <?php echo $SubErr; ?></span>
<p><input class="w3-input w3-padding-16" type="text" placeholder="Message" name="Message"></p>
<span class="error"> <?php echo $MessErr; ?></span>
<p>
<button class="w3-btn w3-grey w3-padding-large w3-hover-green" type="submit" value="Submit" name="pressed">
<i class="fa fa-paper-plane"></i> SEND MESSAGE
</button>
</p>
</form>
<?php
if (isset($_POST["pressed"])) {
if (empty($NameErr && $SubErr && $MessErr && $EmailErr)) {
mail($To, $Subject, $Message, $header);
echo "Email sent.";
} else {
echo "Error.";
}
}
?>
Can you help me? Error validating is on and it doesn't show me any errors.
use isset function instead of empty() to check if the field is posted or not.
example:
if (!isset($_POST["Name"])) {
...
also there is no need to check the request method, $_POST will only catch post requests.
So I've re designed the code structure for you. Generally calling a class and a function will keep your files and your code cleaner.
So with this being said, let me show you some insight. This is where your form will be located for example: form.php
<?php
require ('mail.php');
$send = new Mail();
if (isset($_POST['sendIt']))
{
$send->sendMail($_POST['nameP'], $_POST['email'], $_POST['subject'], $_POST['message']); // Call the class and function
}
?>
<form id="contact" method="post">
<div class="container">
<input type="text" name="nameP" placeholder="Name *" /><br />
<input type="email" name="email" placeholder="Email *"/><br />
<input type="text" name="subject" placeholder="Subject *"><br />
<textarea name="message" id="" cols="30" rows="10"></textarea>
<input type="submit" name="sendIt" id="submit">
</div>
</form>
Then create yourself a mail.php file to store the class and the functions revolving around mailing in general:
<?php
class Mail
{
public function sendMail($name, $email, $subject, $message)
{
if (!empty($name))
{
if (!empty($email))
{
if (!empty($subject))
{
if (!empty($message))
{
$email_to = 'Your#emailAddress';
$header = 'From: ' . $name ."<noreply#youremail>". "\r\n" .
'Reply-To: ' . $email . "\r\n" .
'X-Mailer: PHP/' . phpversion();
#mail($email_to, 'Enquiry Received', 'Name: ' . $name . "\r\n\r\n". 'Email Address: ' .$email."\r\n\r\n" . 'Message: ' .$message."\r\n\r\n". $header);
echo "SUCCESS MESSAGE";
} else {
echo "Please fill in your message";
}
} else {
echo "Please provide a subject.";
}
} else {
echo "Please provide your email address.";
}
} else {
echo "Please provide your name.";
}
}
}
?>
This will generally clear the form if there is an error by default however you can then simply add value="<?php echo $_POST['whateverThisFormIsFor'];?>
I hope this will help and give you some further insight.
The way you're constructing your empty check towards the bottom is incorrect:
if (empty($NameErr && $SubErr && $MessErr && $EmailErr)){
The only way that this will evaluate to false is if all of the error messages are set, and the above snippet will break before PHP 5.5 (as Felippe mentioned in the comments). What you want instead is the below; it returns true only if none of the error messages are set:
if (empty($NameErr)
&& empty($SubErr)
&& empty($MessErr)
&& empty($EmailErr)) {
Another way to do this would be to
extract the validation logic into methods for readability,
read off of an $errors array instead of $NameErr, $SubjectErr, etc.
keep POST logic together (instead of split between the beginning and end)
To those ends, I've rewritten your snippet below:
<?php
function validateName($input)
{
if (empty($input)) {
return 'Name is required';
}
if (preg_match("/^[a-zA-Z ]*$/", $input) != 1) {
return 'Name may only contain letters and spaces';
}
return null;
}
function validateEmail($input)
{
if (empty($input)) {
return 'Email is required';
}
if (filter_var($input, FILTER_VALIDATE_EMAIL)) {
return 'Email is in an invalid format';
}
return null;
}
function validateSubject($input)
{
return empty($input) ? 'Subject is required' : null;
}
function validateMessage($input)
{
return empty($input) ? 'Message is required' : null;
}
function test_input($data)
{
return htmlspecialchars(stripslashes(trim($data)));
}
$errors = [];
$notification = '';
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = test_input($_POST['name'] ?: '');
$email = test_input($_POST['email'] ?: '');
$subject = test_input($_POST['subject'] ?: '');
$message = test_input($_POST['message'] ?: '');
if (($error = validateName($name)) !== null) {
$errors['name'] = $error;
}
if (($error = validateEmail($email)) !== null) {
$errors['email'] = $error;
}
if (($error = validateSubject($subject)) !== null) {
$errors['subject'] = $error;
}
if (($error = validateMessage($message)) !== null) {
$errors['message'] = $error;
}
if (empty($errors)) {
$headers = [
"From: $name <$email>",
"Content-Type: text/plain",
];
$to = "xxx#gmail.com";
mail($to, $subject, $message, implode("\r\n", $headers));
$notification = 'The email was sent!';
} else {
$notification = 'The email could not be sent; please check below for errors.';
}
}
?>
<form method="post" action="<?= htmlspecialchars($_SERVER['PHP_SELF']) ?>">
<?php if (!empty($notification)): ?><p><?= $notification ?></p><?php endif; ?>
<p><input class="w3-input w3-padding-16" type="text" placeholder="Name" name="name" required></p>
<?php if (isset($errors['name'])): ?><span class="error"> <?= $errors['name'] ?></span><?php endif; ?>
<p><input class="w3-input w3-padding-16" type="email" placeholder="Email" name="email" required></p>
<?php if (isset($errors['email'])): ?><span class="error"> <?= $errors['email'] ?></span><?php endif; ?>
<p><input class="w3-input w3-padding-16" type="text" placeholder="Subject" name="subject" required></p>
<?php if (isset($errors['subject'])): ?><span class="error"> <?= $errors['subject'] ?></span><?php endif; ?>
<p><input class="w3-input w3-padding-16" type="text" placeholder="Message" name="message" required></p>
<?php if (isset($errors['message'])): ?><span class="error"> <?= $errors['message'] ?></span><?php endif; ?>
<p>
<button class="w3-btn w3-grey w3-padding-large w3-hover-green" type="submit">
<i class="fa fa-paper-plane"></i> SEND MESSAGE
</button>
</p>
</form>
Related
I'm making a form using PHP and HTML. I want the form to use a predetermined value if the user does not fill out the form.
Default value:
Name: Jhon
Email: #example.com
Message: Without message
This is the PHP code that I use to process data:
if(isset($_POST['submitted'])) {
if(trim($_POST['contactName']) === '') {
$nameError = 'Please enter your name.';
$hasError = true;
} else {
$name = trim($_POST['contactName']);
}
if(trim($_POST['email']) === '') {
$emailError = 'Please enter your email address.';
$hasError = true;
} else if (!preg_match("/^[[:alnum:]][a-z0-9_.-]*#[a-z0-9.-]+\.[a-z]{2,4}$/i", trim($_POST['email']))) {
$emailError = 'You entered an invalid email address.';
$hasError = true;
} else {
$email = trim($_POST['email']);
}
if(trim($_POST['comments']) === '') {
$commentError = 'Please enter a message.';
$hasError = true;
} else {
if(function_exists('stripslashes')) {
$comments = stripslashes(trim($_POST['comments']));
} else {
$comments = trim($_POST['comments']);
}
}
if(!isset($hasError)) {
$emailTo = get_option('tz_email');
if (!isset($emailTo) || ($emailTo == '') ){
$emailTo = get_option('admin_email');
}
$subject = '[PHP Snippets] From '.$name;
$body = "Name: $name \n\nEmail: $email \n\nComments: $comments";
$headers = 'From: '.$name.' <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;
wp_mail($emailTo, $subject, $body, $headers);
$emailSent = true;
}
}
And here is the HTML I used:
<?php if(isset($emailSent) && $emailSent == true) { ?>
<div class="thanks">
<p>Thanks, your email was sent successfully.</p>
</div>
<?php } else { ?>
<?php the_content(); ?>
<?php if(isset($hasError) || isset($captchaError)) { ?>
<p class="error">Sorry, an error occured.<p>
<?php } ?>
<form action="<?php the_permalink(); ?>" id="contactForm" method="post">
<ul class="contactform">
<li>
<label for="contactName">Name:</label>
<input type="text" name="contactName" id="contactName" value="<?php if(isset($_POST['contactName'])) echo $_POST['contactName'];?>" class="required requiredField" />
<?php if($nameError != '') { ?>
<span class="error"><?=$nameError;?></span>
<?php } ?>
</li>
<li>
<label for="email">Email</label>
<input type="text" name="email" id="email" value="<?php if(isset($_POST['email'])) echo $_POST['email'];?>" class="required requiredField email" />
<?php if($emailError != '') { ?>
<span class="error"><?=$emailError;?></span>
<?php } ?>
</li>
<li><label for="commentsText">Message:</label>
<textarea name="comments" id="commentsText" rows="20" cols="30" class="required requiredField"><?php if(isset($_POST['comments'])) { if(function_exists('stripslashes')) { echo stripslashes($_POST['comments']); } else { echo $_POST['comments']; } } ?></textarea>
<?php if($commentError != '') { ?>
<span class="error"><?=$commentError;?></span>
<?php } ?>
</li>
<li>
<input type="submit">Send email</input>
</li>
</ul>
<input type="hidden" name="submitted" id="submitted" value="true" />
</form>
<?php } ?>
How do I make the values sent use the default values if the user does not fill out the form?
use ?: ( Ternary Operator)
$email = $_POST['email'] ?: 'default Email';
The above is identical to this if/else statement
if (empty($_POST['email'])) {
$email = 'default Email';
} else {
$email = $_POST['email'];
}
use this logic for those element you want to set a default value.
You can use the ?? operator:
$email = $_POST['email'] ?? 'defaultemail#example.com';
It's the equivalent to doing a empty() and assigning the default value if it is empty:
$email = NULL;
if (!empty($_POST['email'])) {
$email = $_POST['email'];
} else {
$email = 'defaultemail#example.com';
}
Before I get into it I would like to say that this did send emails from my local server so I have everything set up. After adding this form validation it no longer sends emails or shows errors. It just refreshes the page. I'm new to php coding so I'm sure I just have an if statement in the wrong order or something like that.
HTML
<section id="contact">
<h1 class="section-header">Contact Us Directly</h1>
<h4 class="text-center">Have any quesitons not answered in the <span>Questions Page</span>.</h4>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="POST">
<label for="fname">First Name</label>
<input type="text" id="fname" name="firstname" value="<?php $firstname ?>" placeholder="Your name.." tabindex="1" autofocus>
<span class="error"><?php $firstname_error ?></span>
<label for="lname">Last Name</label>
<input type="text" id="lname" name="lastname" value="<?php $lastname ?>" placeholder="Your last name.." tabindex="2">
<span class="error"><?php $lastname_error ?></span>
<label for="email">Email</label>
<input type="text" id="email" name="email" value="<?php $email ?>" placeholder="Your email.." tabindex="3">
<span class="error"><?php $email_error ?></span>
<label for="message">Message</label>
<textarea id="subject" name="message" value="<?php $message ?>" placeholder="Write something.." style="height:200px" tabindex="4"> </textarea>
<span class="error"><?php $message_error ?></span>
<input type="submit" value="Submit" tabindex="5">
<span class="success"><?php $success ?></span>
</form>
</section>
PHP
<?php
$firstname_error = $lastname_error = $email_error = $message_error = "";
$firstname = $lastname = $email = $message = $success = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["firstname"])) {
$firstname_error = "First name is required";
} else {
$firstname = test_input($_POST["firstname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$firstname)) {
$firstname_error = "Only letters and white space allowed";
}
}
if (empty($_POST["lastname"])) {
$lastname_error = "Last name is required";
} else {
$lastname = test_input($_POST["lastname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$lastname)) {
$lastname_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["message"])) {
$message = "";
} else {
$message = test_input($_POST["message"]);
}
if ($firstname_error == '' and $lastname_error == '' and $email_error == '' and $message_error == '' ){
$message_body = '';
unset($_POST['submit']);
foreach ($_POST as $key => $value){
$message_body .= "$key: $value\n";
}
$EmailFrom = localhost;
$EmailTo = "testrepairmail69#gmail.com";
$Subject = "New Order From tabletscreenfixer.com";
if (mail($EmailTo, $Subject, $message)){
$success = "Message sent, thank you for contacting us!";
$firstname = $lastname = $email = $message = '';
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
Your Code is begging for some improvements as #R Smith mentioned; nevertheless this version works; i have tested on my pc.
<?php
$firstname_error = $lastname_error = $email_error = $message_error = "";
$firstname = $lastname = $email = $message = $success = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["firstname"])) {
$firstname_error = "First name is required";
} else {
$firstname = test_input($_POST["firstname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$firstname)) {
$firstname_error = "Only letters and white space allowed";
}
}
if (empty($_POST["lastname"])) {
$lastname_error = "Last name is required";
} else {
$lastname = test_input($_POST["lastname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$lastname)) {
$lastname_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["message"])) {
$message = "";
} else {
$message = test_input($_POST["message"]);
}
if ($firstname_error == '' and $lastname_error == '' and $email_error == '' and $message_error == '' ){
$message_body = '';
unset($_POST['submit']);
// var_dump($_POST); exit();
foreach ($_POST as $key => $value){
$message_body .= "$key: $value\n";
}
$EmailFrom = "test#gamil.com";
$EmailTo = "tabletscreenfixer.com";//-> the message will be sent to this address if you have configure mail stuff well
$Subject = "New Order From tabletscreenfixer.com";
if (mail($EmailTo, $Subject, $message)){
$success = "Message sent, thank you for contacting us!";
$firstname = $lastname = $email = $message = '';
}else{
echo "Failure";
}
}else{
echo "Failure 2";
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<html>
<head>
<title>Test</title>
</head>
<body>
<section id="contact">
<h1 class="section-header">Contact Us Directly</h1>
<h4 class="text-center">Have any quesitons not answered in the <span>Questions Page</span>.</h4>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="POST">
<label for="fname">First Name</label>
<input type="text" id="fname" name="firstname" value="<?php echo $firstname ?>" placeholder="Your name.." tabindex="1" autofocus>
<span class="error"><?php echo $firstname_error ?></span>
<label for="lname">Last Name</label>
<input type="text" id="lname" name="lastname" value="<?php echo $lastname ?>" placeholder="Your last name.." tabindex="2">
<span class="error"><?php echo $lastname_error ?></span>
<label for="email">Email</label>
<input type="text" id="email" name="email" value="<?php echo $email ?>" placeholder="Your email.." tabindex="3">
<span class="error"><?php echo $email_error ?></span>
<label for="message">Message</label>
<textarea id="subject" name="message" value="<?php echo $message ?>" placeholder="Write something.." style="height:200px" tabindex="4"> </textarea>
<span class="error"><?php echo $message_error ?></span>
<input type="submit" value="Submit" tabindex="5">
<span class="success"><?php $success ?></span>
</form>
</section>
</body>
</html>
EDIT: Missing echo in the input value attribute;
Hope it helps;
Add some debugging. For example, everywhere you have an error, increment a error counter. Something like this:
if (empty($_POST["email"])) {
$email_error = "Email is required";
$errors++;
} 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";
}
}
Then, at the end, instead of the long if condition:
if ($firstname_error == '' and $lastname_error == '' and $email_error == '' and $message_error == '' ){
You can use something like:
if ($errors == 0){
Which indicates no errors. Then, inside that if, when you try to send the mail, check for failure:
if (mail($EmailTo, $Subject, $message)){
$success = "Message sent, thank you for contacting us!";
$firstname = $lastname = $email = $message = '';
}
else {
echo "The mail command failed!!";
}
Finally, give yourself some sort of indicator that there were errors, just for your testing phase. You can remove this else (or even add better styling and keep it):
if ($errors == 0){
// snip - lines of code in here removed to keep this snippet readable. this is your test and send mail logic.
}
else {
echo "You've got $errors errors! You need to correct them!";
}
With these changes, you should be able to find your issues quickly. As I said, you can also remove some of this code (like the echo statements) once you've finished your debugging.
Good luck!
I am making a PHP form and not sure how to go about having the code say "message delivered" when clicking submission and having it validate correctly. Here is my code so far. I realize that the message appears anytime you click submit. Thank you for your patience.
<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $comment = $message = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["comment"]);
}
if (isset($_POST["submit"])) {
$message = "Message has been delivered";
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<div class="cntr">
<h2>Contact Form</h2>
<p><span class="error">* required field.</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div class="field">
<label for="name">Name </label>
<br>
<input type="text" name="name">
<span class="error">*<?php echo $nameErr;?></span>
</div>
<div class="field">
<label for="email">Email</label>
<br>
<input type="text" name="email">
<span class="error">* <?php echo $emailErr;?></span>
</div>
<div class="field">
<label for="message">Message</label>
<br>
<textarea name="comment" rows="8" cols="40"></textarea>
</div>
<button type="submit" class="email" name="submit" value="Submit">Submit</button>
<?php echo $message; ?><br/>
</form>
</div>
Use
if (isset($_POST["submit"]) && empty($nameErr) && empty($genderErr) && empty($emailErr) && empty($websiteErr)) {
$message = "Message has been delivered";
}
instead of
if (isset($_POST["submit"])) {
$message = "Message has been delivered";
}
Because isset($_POST["submit"]) is true when ever you do a submit , so you need to check the error variables are empty also . if the error variables are empty that means your code validated and passed .
There's a couple of things that I need some help on:
I have a function called isValid that is not checking if the emails entered in my form are valid?
How can i have my error messages display inside the form's text field?
Any help is greatly appreciated!
Below is my code:
<?php
//Set Variables to Empty String
$Email = " ";
$Subject = " ";
$Name = " ";
$Message = " ";
$error = " ";
if(isset($_POST['submit']) )
{
if (empty($_POST["Email"]))
{
$error = "** Enter a valid email";
}
else
{
$Email = isValid($_POST["Email"]);
}
if (empty($_POST["Subject"]))
{
$error = "** Enter a subject";
}
else
{
$Subject= test_input($_POST["Subject"]);
}
if (empty($_POST["Name"]))
{
$error = "** Enter your name";
}
else
{
$Name= test_input($_POST["Name"]);
}
if (empty($_POST["Message"]))
{
$error = "** Enter your message";
}
else
{
$Message= test_input($_POST["Message"]);
}
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
//isValid checks if email address is a valid one
function isValid($edata)
{
return(preg_match("/^[-_.[:alnum:]]+#((([[:alnum:]]|[[:alnum:]][[:alnum:]-]* [[:alnum:]])\.)+(ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum|mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)$|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][ 0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i", $edata));
}
?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<p><label>From (Email):</label></p>
<input type="text" size="35" name="Email">
<span class="error"><?php echo $error;?></span>
<br><br>
<p><label>Subject:</label></p>
<input type="text" size="35" name="Subject">
<span class="error"><?php echo $error;?></span>
<br><br>
<p><label>Name:</label></p>
<input type="text" size="35" name="Name">
<span class="error"><?php echo $error;?></span>
<br><br>
<p><label>Message:</label></p>
<textarea type="text" cols="38" rows="6" name="Message"></textarea>
<span class="error"><?php echo $error;?></span>
<br><br>
<input type="submit" name="submit" value="submit">
<input type="reset" value="Reset">
</form>
<?php
if(empty($error))
{
// the email will be sent here
$to = "#gmail.com";
// the email subject
$subject = 'Message from XXXX website from: ' . $Name;
// the mail message
$msg .= "\r\nEmail: $Email";
$msg .= "\r\n\nSubject: $Subject";
$msg .= "\r\n\nName: $Name";
$msg .= "\r\n\nMessage: $Message";
mail($to, $subject, $msg, "From: $Email\r\nReply-To: $Email\r\nReturn-Path: $Email\r\n");
}
?>
<p>Thank you <b><?=$Name;?></b> for your message. Expect a response in 1 - 3 business days</p>
validate functions
<?php
$email_a = 'joe#example.com';
$email_b = 'bogus';
if (filter_var($email_a, FILTER_VALIDATE_EMAIL)) {
echo "This ($email_a) email address is considered valid.";
}
if (filter_var($email_b, FILTER_VALIDATE_EMAIL)) {
echo "This ($email_b) email address is considered valid.";
}
?>
for second question, change your code like this:
if (empty($_POST["Email"]))
{
$error['Email'] = "** Enter a valid email";
}
.
.
.
if (empty($_POST["Name"]))
{
$error['Name'] = "** Enter your name";
}
.
.
.
<input type="text" size="35" name="Email">
<span class="error"><?php echo $error['Email'];?></span>
<input type="text" size="35" name="Name">
<span class="error"><?php echo $error['Name'];?></span>
I am not a PHP programmer, but have used it a touch, enough to put in a contact form. However, I am trying to add a captcha field, which now works but the form does not validate it - so it submits no matter what
Can anybody help please? sorry if the code is messy and thanks in advance
code at the top of my page
<?php session_start() ?>
<?php
//If the form is submitted
if(isset($_POST['submit'])) {
//Check to make sure that the name field is not empty
if(trim($_POST['name']) == '') {
$hasError = true;
} else {
$name = trim($_POST['name']);
}
//Check to make sure that the subject field is not empty
if(trim($_POST['subject']) == '') {
$hasError = true;
} else {
$subject = trim($_POST['subject']);
}
//Check to make sure sure that a valid email address is submitted
if(trim($_POST['email']) == '') {
$hasError = true;
} else if (!eregi("^[A-Z0-9._%-]+#[A-Z0-9._%-]+\.[A-Z]{2,4}$", trim($_POST['email'])))
{
$hasError = true;
} else {
$email = trim($_POST['email']);
}
//Check to make sure comments were entered
if(trim($_POST['message']) == '') {
$hasError = true;
} else {
if(function_exists('stripslashes')) {
$message = stripslashes(trim($_POST['message']));
} else {
$message = trim($_POST['message']);
}
/*captcha 2*/
if(isset($_POST["captcha"])) {
$hasError = true;
} else {
if($_SESSION["captcha"]==$_POST["captcha"]) {
}
}
//CAPTHCA is valid; proceed the message: save to database, send by e-mail ...
//If there is no error, send the email
if(!isset($hasError)) {
$emailTo = 'email address'; //Put your own email address here
$emailTo = 'email address'; //Put your own email address here
$body = "Name: $name \n\nEmail: $email \n\nSubject: $subject \n\nMessage:\n $message";
$headers = 'From: website form <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' .
$email;
mail($emailTo, $subject, $body, $headers);
$emailSent = true;
}
}
?>
Code in the form:
[php]<?php if(isset($hasError)) { //If errors are found ?>
<p class="error">Please check if you've filled all the fields with valid information. Thank you.</p>
<?php } ?>
<?php if(isset($emailSent) && $emailSent == true) { //If email is sent ?>
<p><strong>Email Successfully Sent!</strong></p>
<p>Thank you <strong><?php echo $name;?></strong> for contacting us. Your email was successfully sent and we will be in touch with you soon.</p>
<?php } ?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" id="contactform">
<div>
<p>
<label for="name">Name</label><br />
<input type="text" name="name" value="" id="name" class="required">
</p>
</div>
<div>
<p>
<label for="email">Email</label><br />
<input type="text" name="email" value="" id="email" class="required">
</p>
</div>
<div>
<p>
<label for="subject">Subject</label><br />
<input type="text" name="subject" value="" id="subject" class="required">
</p>
</div>
<div style="margin-bottom:25px;">
<p>
<label for="message">Message</label><br />
<textarea rows="5" name="message" value="" id="message" class="required"></textarea>
</p>
</div>
<div style="margin-bottom:25px;">
<img src="captcha.php" alt="captcha image">
<p>
<label for="captcha">(antispam code, 3 black symbols)</label><br />
<input type="text" name="captcha" maxlength="3" id="captcha" class="required">
</p>
</div>
<input type="submit" value="Send Message" name="submit" />
</form>
[/php]
[edit ] 2011-12-20 8:22pm CST - updated the second block of code with the final code that the OP is using - based on off site chat.
There's a better way to write the code. I'm putting an example of this below. Ask questions and I'll update the code with comments explaining. I revamped the if statement you had for the captcha so that it didn't need a double if. Using || (or) in the if statement causes PHP to stop after testing the first condition (if the first condition evaluates to true). Therefore, if the variable is not set it never moves on to the comparison of POST with SESSION.
Also, I defaulted your hasError variable to false, and am testing for the boolean value. This is better because it makes sense. Think about the programmers who will come after you. If it makes sense, it'll be easier to work with. You might be that programmer :)
[edited to add session_start();]
<?php
session_start();
// default value
$hasError = false;
//If the form is submitted
if(isset($_POST['submit'])) {
//Check to make sure that the name field is not empty
if(trim($_POST['name']) == '') {
$hasError = true;
} else {
$name = trim($_POST['name']);
}
//Check to make sure that the subject field is not empty
if(trim($_POST['subject']) == '') {
$hasError = true;
} else {
$subject = trim($_POST['subject']);
}
//Check to make sure sure that a valid email address is submitted
if(trim($_POST['email']) == '') {
$hasError = true;
} else if (!eregi("^[A-Z0-9._%-]+#[A-Z0-9._%-]+\.[A-Z]{2,4}$", trim($_POST['email']))) {
$hasError = true;
} else {
$email = trim($_POST['email']);
}
//Check to make sure comments were entered
if( trim($_POST['message']) == '') {
$hasError = true;
} else {
if(function_exists('stripslashes')) {
$message = stripslashes(trim($_POST['message']));
} else {
$message = trim($_POST['message']);
}
}
if( ! isset( $_POST["captcha"] ) || $_SESSION["captcha"] != $_POST["captcha"] ) {
$hasError = true;
echo 'CAPTHCA is not valid; ignore submission<br>';
echo $_POST['captcha' . ' != ' . $_SESSION['captcha'] . '<br>';
}
//If there is no error, send the email
if( $hasError == false ) {
$emailTo = 'email#email.com'; //Put your own email address here
$emailTo = 'email#email.com'; //Put your own email address here
$body = "Name: $name \n\nEmail: $email \n\nSubject: $subject \n\nMessage:\n $message";
// !!!!!!!!!!!!!!!! REMOVE \r\n from $emailTo or your form will be hacked !!!!!!!!!!!!!!!!!!!!!!
$headers = 'From: website form <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;
mail($emailTo, $subject, $body, $headers);
$emailSent = true;
} else {
}
}
[edit - full code, edited and (hopefully) improved]
<?php
session_start();
function clean_for_email( $inbound )
{
return str_replace( array( "\n", "\r" ), "", $inbound );
}
// I really like the name of this function. :D
function outputInput( $name, $required )
{
$attribs[] = "name=\"{$name}\"";
$attribs[] = "id=\"{$name}\"";
$attribs[] = $required?'class="required"':'';
$attribs[] = 'type="text"';
if ( count( $_POST ) && array_key_exists( $name, $_POST ) )
{
$attribs[] = 'value="' . htmlspecialchars( $_POST[$name] ) . '"';
}
echo '<input ' . implode( ' ', $attribs ) . '>';
}
//------------------------------------------------------------------------
function outputTextarea( $name, $required, $rows = 5 )
{
$attribs[] = "name=\"{$name}\"";
$attribs[] = "id=\"{$name}\"";
$attribs[] = $required?'class="required"':'';
$attribs[] = 'rows="5"';
$value = '';
if ( count( $_POST ) && array_key_exists( $name, $_POST ) )
{
$value = htmlspecialchars( $_POST[$name] );
}
echo '<textarea ' . implode( ' ', $attribs ) . '>' . $value . '</textarea>';
}
// default value
$hasError = false;
$emailSent = false;
//If the form is submitted
if( count( $_POST ) && isset($_POST['submit'] ) ) {
//Check to make sure that the name field is not empty
if(trim($_POST['name']) == '') {
$hasError = true;
} else {
$name = trim($_POST['name']);
}
//Check to make sure that the subject field is not empty
if(trim($_POST['subject']) == '') {
$hasError = true;
} else {
$subject = trim($_POST['subject']);
}
//Check to make sure sure that a valid email address is submitted
if(trim($_POST['email']) == '') {
$hasError = true;
} else if ( ! preg_match( '/^.+#.+$/i', trim( $_POST['email'] ) ) ) {
$hasError = true;
} else {
$email = trim($_POST['email']);
}
//Check to make sure comments were entered
if( trim($_POST['message']) == '') {
$hasError = true;
} else {
if(function_exists('stripslashes')) {
$message = stripslashes(trim($_POST['message']));
} else {
$message = trim($_POST['message']);
}
}
if ( ! array_key_exists( 'captcha', $_POST ) || $_SESSION['captcha'] != $_POST["captcha"] ) {
$hasError = true;
}
if( ! $hasError )
{
$captchaValid = true;
//If there is no error, send the email
if( $hasError == false ) {
$emailTo = 'xxx'; //Put your own email address here
$body = "Name: $name \n\nEmail: $email \n\nSubject: $subject \n\nMessage:\n $message";
$headers = 'From: website form <'.clean_for_email( $emailTo ).'>' . "\r\n" . 'Reply-To: ' . clean_for_email( $email );
mail($emailTo, $subject, $body, $headers);
$emailSent = true;
} else {
}
}
}
?>
<? if( $hasError ) : ?>
<p class="error">Please check if you've filled all the fields with valid information Thank you.</p>
<? endif; ?>
<? if( $emailSent == true) : ?>
<p><strong>Email Successfully Sent!</strong></p>
<p>Thank you <strong><?php echo $name;?></strong> for contacting us. Your email was successfully sent and we will be in touch with you soon.</p>
<? endif; ?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" id="contactform">
<div>
<p>
<label for="name">Name</label><br />
<? outputInput( 'name', true ); ?>
</p>
</div>
<div>
<p>
<label for="email">Email</label><br />
<? outputInput( 'email', true ); ?>
</p>
</div>
<div>
<p>
<label for="subject">Subject</label><br />
<? outputInput( 'subject', true ); ?>
</p>
</div>
<div style="margin-bottom:25px;">
<p>
<label for="message">Message</label><br />
<? outputTextarea( 'message', true ); ?>
</p>
</div>
<div style="margin-bottom:25px;">
<img src="captcha.php" alt="captcha image">
<p>
<label for="captcha">(antispam code, 3 black symbols)</label><br />
<? outputInput( 'captcha', true ); ?>
</p>
</div>
<input type="submit" value="Send Message" name="submit" />
</form>
if(isset($_POST["captcha"]))
You're missing a bracket.
Edited to show entire code.... Brackets added for captcha conditionals which were missing. As is, your code did not check if the captcha was set via post. It was only checking the session variable against the post variable. If both were blank, the form would mail. You may still have issues with captcha.php or the session variable.
<?php
//If the form is submitted
if(isset($_POST['submit'])) {
//Check to make sure that the name field is not empty
if(trim($_POST['name']) == '') {
$hasError = true;
} else {
$name = trim($_POST['name']);
}
//Check to make sure that the subject field is not empty
if(trim($_POST['subject']) == '') {
$hasError = true;
} else {
$subject = trim($_POST['subject']);
}
//Check to make sure sure that a valid email address is submitted
if(trim($_POST['email']) == '') {
$hasError = true;
} else if (!eregi("^[A-Z0-9._%-]+#[A-Z0-9._%-]+\.[A-Z]{2,4}$", trim($_POST['email'])))
{
$hasError = true;
} else {
$email = trim($_POST['email']);
}
//Check to make sure comments were entered
if(trim($_POST['message']) == '') {
$hasError = true;
} else {
if(function_exists('stripslashes')) {
$message = stripslashes(trim($_POST['message']));
} else {
$message = trim($_POST['message']);
}
}
/*captcha 2*/
if(isset($_POST["captcha"])) {
if($_SESSION["captcha"]==$_POST["captcha"])
{
//CAPTHCA is valid; proceed the message: save to database, send by e-mail ...
//If there is no error, send the email
if(!isset($hasError)) {
$emailTo = 'enquiries#sjbprojects.com'; //Put your own email address here
$emailTo = 'sjbullen#gmail.com'; //Put your own email address here
$body = "Name: $name \n\nEmail: $email \n\nSubject: $subject \n\nMessage:\n $message";
$headers = 'From: SJB Projects website form <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;
mail($emailTo, $subject, $body, $headers);
$emailSent = true;
}
else
{
echo 'CAPTHCA is not valid; ignore submission';
}
}
} else {
///message here if CAPTCHA is not set (via post)
}
}
?>
<?php if(isset($hasError)) { //If errors are found ?>
<p class="error">Please check if you've filled all the fields with valid information. Thank you.</p>
<?php } ?>
<?php if(isset($emailSent) && $emailSent == true) { //If email is sent ?>
<p><strong>Email Successfully Sent!</strong></p>
<p>Thank you <strong><?php echo $name;?></strong> for contacting SJB Projects. Your email was successfully sent and we will be in touch with you soon.</p>
<?php } ?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" id="contactform">
<div>
<p>
<label for="name">Name</label><br />
<input type="text" name="name" value="" id="name" class="required">
</p>
</div>
<div>
<p>
<label for="email">Email</label><br />
<input type="text" name="email" value="" id="email" class="required">
</p>
</div>
<div>
<p>
<label for="subject">Subject</label><br />
<input type="text" name="subject" value="" id="subject" class="required">
</p>
</div>
<div style="margin-bottom:25px;">
<p>
<label for="message">Message</label><br />
<textarea rows="5" name="message" value="" id="message" class="required"></textarea>
</p>
</div>
<div style="margin-bottom:25px;">
<img src="captcha.php" alt="captcha image">
<p>
<label for="captcha">(antispam code, 3 black symbols)</label><br />
<input type="text" name="captcha" maxlength="3" id="captcha" class="required">
</p>
</div>
<input type="submit" value="Send Message" name="submit" />
</form>