My Contact Form sending blank emails when the page is viewed - php

My contact form is sending black emails every time I visit the page, and the sends another whenever someone fills out the form and clicks send. I am trying to learn how to validate data for my contact form and have had little luck all day. I know very little php or javascript code as of yet but have done my best from previously written code.
I tried to use this http://www.inmotionhosting.com/support/edu/website-design/using-php-and-mysql/how-to-create-a-custom-php-contact-form to help with code.
Any ideas?
<form action="" method="post" style="width:100%;">
Name*<br> <input type="text" name="name" style="width:50%;" ><br/><br/>
Email*<br> <input type="text" name="email" style="width:50%;"> <br/><br/>
Phone*<br> <input type="text" name="phone" style="width:50%"> <br/><br/>
<input name="submitted" type="submit" value="Send" >
<input name="" type="reset" value"Reset">
</form>
<?php
if (isset($_REQUEST['submitted'])) {
// Initialize error array.
$errors = array();
// Check for a name
if (!empty($_REQUEST['name'])) {
$name = $_REQUEST['name'];
$pattern = "/^[a-zA-Z0-9\_]{2,20}/";]
if (preg_match($pattern,$name)) {
$name = $_REQUEST['name'];
} else {
$errors[] = 'Your Name can only contain _, 1-9, A-Z or a-z 2-20 long.';
}
} else {
$errors[] = 'You forgot to enter your name.';
}
//Check for a valid phone number
if (!empty($_REQUEST['phone'])) {
$phone = $_REQUEST['phone'];
$pattern = "/^[0-9\_]{7,20}/";
if (preg_match($pattern,$phone)) {
$phone = $_REQUEST['phone'];
} else {
$errors[] = 'Your phone number can only be numbers.';
}
} else {
$errors[] = 'You forgot to enter your phone number.';
}
//Check for a valid email
if (!filter_var($_REQUEST['email'], FILTER_VALIDATE_EMAIL)) {
$errors[] = 'The email provided is not valid.';
}
} else {
$email = $_REQUEST['email'];
}
//End of validation
if (empty($errors)) {
$from = "From: " . $_REQUEST['email'];
$to = "myemail#myemail.com";
$subject = "A comment from " . $name . "";
$message = "Message from " . $name . "
Phone: " . $phone . "
Email: " . $_REQUEST['email'] . "";
mail($to,$subject,$message, $from);
}
//Print Errors
if (isset($_REQUEST['submitted'])) {
// Print any error messages.
if (!empty($errors)) {
echo '<hr /><h3 >The following occurred:</h3><ul>';
// Print each error.
foreach ($errors as $msg) {
echo '<li>'. $msg . '</li>';
}
echo '</ul><h3 >Your mail could not be sent due to input errors.</h3><hr />';
} else {
echo '<hr /><h3 align="center" >Your mail was sent. Thank you!</h3><hr /><p>Below is the message that you sent.</p>';
echo "Message from " . $name . "<br />Phone: ".$phone."<br />Email:" . $email;
}
}
//End of errors array
?>

You're sending mail outside the if (isset($_POST['submitted'])) block. I think the problem is that you have an extra close brace here:
//Check for a valid email
if (!filter_var($_REQUEST['email'], FILTER_VALIDATE_EMAIL)) {
$errors[] = 'The email provided is not valid.';
} // <<===== HERE
} else {
$email = $_REQUEST['email'];
}
As a result, the else clause isn't connected to the email validation, it's connected to if (isset($_POST['submitted'])). So when the form hasn't been submitted, you set $email and then you go into the code that sends email.

An array that hasn't been declared is still empty.
change
if (empty($errors)) {
to
if (isset($errors) && empty($errors)) {

Related

header Location isn't transferring [duplicate]

This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
Closed 5 years ago.
I have form in my site example.com/pp.php and that formĀ“s action is pp.php because that script is not some external file, but inside of that page. The problem is I need to put header("Location: http://example.com/pp.php#contactForm"); because after pressing Send button I want to reload page on exact position which is /pp.php#contactForm. But header Location is not working.
<form action="pp.php" method="post">
<label>Name:</label>
<input type="text" name="name" value="<?php if($_POST['name']) {
echo $_POST['name']; } ?>" />
<label>Email:</label>
<input type="text" name="email" value="<?php if($_POST['email'])
{ echo $_POST['email']; } ?>" />
<label>Message:</label><br />
<textarea name="message" rows="20" cols="20"><?php
if($_POST['message']) { echo $_POST['message']; } ?></textarea>
<label><img src="captcha.php"></label>
<input type="text" name="code"> <br />
<input type="submit" class="submit" name="submit" value="Send
message" />
</form>
This is php
<?php
if (isset($_POST['submit'])) {
$error = "";
if (!empty($_POST['name'])) {
$name = $_POST['name'];
} else {
$error .= "You didn't type in your name. <br />";
}
if (!empty($_POST['email'])) {
$email = $_POST['email'];
if (!preg_match("/^[a-z0-9]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*
(\.[a-z]{2,3})$/i", $email)){
$error .= "The e-mail address you entered is not valid. <br/>";
}
} else {
$error .= "You didn't type in an e-mail address. <br />";
}
if (!empty($_POST['message'])) {
$message = $_POST['message'];
} else {
$error .= "You didn't type in a message. <br />";
}
if(($_POST['code']) == $_SESSION['code']) {
$code = $_POST['code'];
} else {
$error .= "The captcha code you entered does not match. Please try
again. <br />";
}
if (empty($error)) {
$from = 'From: ' . $name . ' <' . $email . '>';
$to = "mail#gmail.com";
$subject = "New contact form message";
$content = $name . " has sent you a message: \n" . $message;
$success = "<h3>Thank you! Your message has been sent!</h3>";
mail($to,$subject,$content,$from);
}
}
?>
<?php
if (!empty($error)) {
echo '<p class="error"><strong>Your message was NOT sent<br/> The
following error(s) returned:</strong><br/>' . $error . '</p>';
} elseif (!empty($success)) {
echo $success;
}
header("Location: http://example.com/pp.php#contactForm");
?>
You can't redirect with header() after outputting to the DOM:
Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP.
As such, you'll need to remove the echo statements in your lines:
if (!empty($error)) {
echo '<p class="error"><strong>Your message was NOT sent<br/> The
following error(s) returned:</strong><br/>' . $error . '</p>';
} elseif (!empty($success)) {
echo $success;
}
Before calling:
header("Location: http://example.com/pp.php#contactForm");
Try this:
header('Location: pp.php#contactForm');
And make sure you do not output any html tag through anyway before this line.
like the echo $success;

PHP email form not posting name or phone number

I can't seem to figure out why my php isn't sending the name and phone number to the email. Email and message is working fine.
Here is my HTML:
<form method="POST" name="contact_form" action="php.php">
<label for='fname'>Name: </label>
<input type="text" name="fname">
<label for='email'>Email: </label>
<input type="text" name="email">
<label for='phone'>Phone: </label>
<input type="text" name="phone">
<label for='message'>Message:</label>
<textarea name="message" rows=8 cols=30><?php echo htmlentities($user_message) ?></textarea>
<label><img src="/captcha.php"></label>
<input type="text" name="code" value="Please enter the code"> <br />
<input type="submit" value="Submit" name='submit' class="quoteButton">
</form>
Here is my PHP:
session_start();
if (isset($_POST['submit'])) {
$error = "";
if (!empty($_POST['fname'])) {
$name = $_POST['fname'];
} else {
$error .= "You didn't type in your name. <br />";
}
if (!empty($_POST['phone'])) {
$name = $_POST['phone'];
} else {
$error .= "You didn't enter your phone. <br />";
}
if (!empty($_POST['email'])) {
$email = $_POST['email'];
if (!preg_match("/^[a-z0-9]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i", $email)){
$error .= "The e-mail address you entered is not valid. <br/>";
}
} else {
$error .= "You didn't type in an e-mail address. <br />";
}
if (!empty($_POST['message'])) {
$message = $_POST['message'];
} else {
$error .= "You didn't type in a message. <br />";
}
if(($_POST['code']) == $_SESSION['code']) {
$code = $_POST['code'];
} else {
$error .= "The captcha code you entered does not match. Please try again. <br />";
}
if (empty($error)) {
$from = 'From: ' . $fname . ' <' . $email . '>';
$to = "mail#domain.com";
$subject = "New contact form message";
$content = $fname . " has sent you a message. \nEmail: $email \nPhone: $phone \nMessage: \n" . $message;
$success = header( 'Location: '' ) ;
mail($to,$subject,$content,$from);
}
}
?>
Any help would be greatly appreciated. Thanks!
1)You named the variable for first name $name but use $fname in the email portion of code
$name = $_POST['fname'];
should be
$fname = $_POST['fname'];
2) You named the variable for first name $name (overwriting your initial assignment) but use $phone in the email portion of code
$name = $_POST['phone'];
should be
$phone = $_POST['phone'];

PHP form validation code used to work fine, stopped working and I don't know why

I have some pretty basic php validation code on my site and it has worked for quite some time. I'm not a php expert by any means (obvious below i'm sure) :), but this code has worked fine for my needs up until now... I recently realized this code has stopped working and I am not sure why. Any help would be appreciated. I thought maybe something changed on the server so I chatted with my host company and they assured me nothing has changed and that it has to be a code error.
Here is the basic portions of the code:
<?php // Handle the form submission
// VALIDATE Forms Required Fileds
//Check for name.
if (strlen($_POST['name']) > 0 ){
$name = $name;
} else {
$name = NULL;
}
//Check email was entered
if (strlen($_POST['email'])=='') {
$email = NULL;
} elseif(!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $_POST['email'])) {
$email = "invalid";
} else {
$email = $email;
}
// END VALIDATION
// If all is ok then handle form
if ((isset($_POST['Submit']) || isset($_POST['Submit_x'])) && ($name && $email && $email != "invalid"))
{
// Capture information and format for email
$subject="Side Nav Form"; // Subject of Email
$body = "Contact Us:\n\n";
$body .="Name..............: " ."$name\n";
$body .="Email.............: " ."$email\n";
$body .="Phone.............: " ."$phone\n\n";
$body .="Reason for inquiry: " ."$inquiryReason1, $inquiryReason2, $inquiryReason3\n";
$body .="Current Website...: " ."$current_site\n\n";
$body .="Comments/Questions: " ."$addtlComments\n";
//Email form results
mail("xxx#xxx.com", $subject, $body, "From:" .$email);
// Display thank you Message if form submitted successfully.
echo '<h3>Thank you!</h3><p>We received your information and will get back to you as soon as possible.</p>';
} else {
// If Validating form: Show validation errors.
if ((isset($_POST['Submit']) || isset($_POST['Submit_x'])) && (!$name || !$email || $email == "invalid")) {
echo '<p class="error">';
if (!$name) {
echo "*Please enter your name.<br />";
}
if (!$email) {
echo "*Please enter your email address.<br />";
}
if ($email == "invalid") {
echo "*Please enter a valid email address. (xxx#xxx.xxx)";
}
echo '</p>';
}
// Display the form if user has not submitted successfully or at all.
?>
<fieldset><label for="name">*Name:</label> <input type="text" name="name" id="name" value="<?php if (isset($_POST['name'])) echo $_POST['name']; ?>" /></fieldset>
<fieldset><label for="email">*Email:</label> <input type="text" name="email" id="email" value="<?php if (isset($_POST['email'])) echo $_POST['email']; ?>" /></fieldset>
... rest of form fields...
<input name="Submit" type="submit" value="Submit" class="submit" />
</form>
<?php
} // End of Form Handler
?>
eregi() is deprecated. Use preg_match() instead. You could also use filter_var(email, FILTER_VALIDATE_EMAIL) to validate emails as well.

PHP Web Form Error Display

I am a PHP newb. I have the following code for a web form. It works fine as is, but I would like to do the following:
Return the errors as an array (?) so I can display errors as individual lines under each input.
and
Disallow the form from being able to be submitted twice.
Any help would be greatly appreciated.
<form id="form1" method="post" action="<?= $_SERVER['PHP_SELF'] ?>">
<fieldset>
<legend>Contact Me</legend>
<?php
if (isset($_POST['Submit'])) {
if ($_POST['firstname'] != "") {
$_POST['firstname'] = filter_var($_POST['firstname'], FILTER_SANITIZE_STRING);
if ($_POST['firstname'] == "") {
$errors .= 'Please enter a valid first name.<br/><br/>';
}
} else {
$errors .= 'Please enter your first name.<br/>';
}
if ($_POST['lastname'] != "") {
$_POST['lastname'] = filter_var($_POST['lastname'], FILTER_SANITIZE_STRING);
if ($_POST['lastname'] == "") {
$errors .= 'Please enter a valid last name.<br/><br/>';
}
} else {
$errors .= 'Please enter your last name.<br/>';
}
if ($_POST['email'] != "") {
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors .= "$email is <strong>NOT</strong> a valid email address.<br/><br/>";
}
} else {
$errors .= 'Please enter your email address.<br/>';
}
if ($_POST['message'] != "") {
$_POST['message'] = filter_var($_POST['message'], FILTER_SANITIZE_STRING);
if ($_POST['message'] == "") {
$errors .= 'Please enter a message to send.<br/>';
}
} else {
$errors .= 'Please enter a message to send.<br/>';
}
if (!$errors) {
$mail_to = '***#****.com';
$subject = 'New Mail from Web Site';
$message = 'From: ' . $_POST['firstname'] . " " . $_POST['lastname'] . "\n";
$message .= 'Email: ' . $_POST['email'] . "\n";
$message .= "Message:\n" . $_POST['message'] . "\n\n";
mail($mail_to, $subject, $message);
echo "<p>Thank you for your email!<br/><br/></p>";
} else {
echo '<div style="color: #00CC00">' . $errors . '<br/></div>';
}
}
?>
<label>First Name:</label>
<input type="text" name="firstname" value="<?php echo $_POST['firstname']; ?>" size="50" />
<label>Last Name:</label>
<input type="text" name="lastname" value="<?php echo $_POST['lastname']; ?>" size="50" />
<label>Email Address:</label>
<input type="text" name="email" value="<?php echo $_POST['email']; ?>" size="50"/>
<label>Message:</label>
<textarea name="message" rows="5" cols="50"><?php echo $_POST['message']; ?></textarea>
<br/>
<input type="submit" class="moveright" name="Submit" value="Submit" />
</fieldset>
</form>
You can use an array for the errors instead of concatenating them into one string. Then you can check for each error at the specified form input.
Sample error check
// instead of: $errors .= 'Please enter a message to send.<br/>';
if ($_POST['message'] == "")
$errors['message'] = 'Please enter a message to send.<br/>';
Sample error display
<label>Message:</label>
<?php if ($errors['message'] != "") echo $errors['message']; ?>
<textarea name="message" rows="5" cols="50"><?php echo $_POST['message']; ?></textarea>
Instead of appending each error to the string, do like the following:
$errors[] = 'error text';
EDIT: as the others have said, it's good practice to initialize the array before starting to set the values, like so: $errors = array();
As for the disallowing the form to be submitted twice, that needs javascript. Here's a link to help: http://www.webmasterworld.com/forum91/3781.htm
To make your errors into an array, initialize it before form processing as:
$errors = array();
if (isset($_POST['Submit'])) {
...
Each time you have an error, rather than concatenating it on with .=, use the [] array append syntax:
$errors[] = 'Please enter a message to send.';
To prevent the form from being submitted twice, we often use a variable in $_SESSION to indicate that it has been completed. On successful submission, set a $_SESSION['success'] flag. Don't forget also to initialize the session at the start of the script:
session_start();
$_SESSION['success'] = FALSE;
$errors = array();
// Only process the form if the session flag isn't set:
if (isset($_POST['Submit']) && !$_SESSION['success']) {
...
// Later, on success,
echo "<p>Thank you for your email!<br/><br/></p>";
// Set the flag to prevent resubmission.
$_SESSION['success'] = TRUE;

HTML/PHP form not sending email

I have a form which does everything right except send the input values to my email, what am I doing wrong? Ps: not using local server, so that's not it.
EDIT: I'm not getting any email whatsoever.
Tried changing the if(isset($_POST['enviar'])) { part but still not working.
Tried the chatty echos. the only if statement that isn't behaving properly is stripslashes. It stops at the else statement.
The form snippet:
<div id="contact-wrapper">
<?php if(isset($hasError)) { //If errors are found ?>
<p class="error">Please check if you entered valid information.</p>
<?php } ?>
<?php if(isset($emailSent) && $emailSent == true) { //If email is sent ?>
<p><strong>Email sent with success!</strong></p>
<p>Thank you for using our contact form <strong><?php echo $name;?></strong>, we will contact you soon.</p>
<?php } ?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" id="contactform">
<div>
<label for="name"><strong>Name:</strong></label>
<input type="text" size="50" name="contactname" id="contactname" value="" class="required" />
</div>
<div>
<label for="email"><strong>E-mail:</strong></label>
<input type="text" size="50" name="email" id="email" value="" class="required email" />
</div>
<div>
<label for="subject"><strong>Subject:</strong></label>
<input type="text" size="50" name="subject" id="subject" value="" class="required" />
</div>
<div>
<label for="message"><strong>Message:</strong></label>
<textarea rows="5" cols="50" name="message" id="message" class="required"></textarea>
</div>
<input type="submit" value="enviar" name="submit" id="submit" />
</form>
</div>
and the PHP:
<?php
//If the form is submitted
if(isset($_POST['submit'])) {
//Check to make sure that the name field is not empty
if(trim($_POST['contactname']) == '') {
$hasError = true;
} else {
$name = trim($_POST['contactname']);
}
//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')) {
$comments = stripslashes(trim($_POST['message']));
} else {
$comments = trim($_POST['message']);
}
}
//If there is no error, send the email
if(!isset($hasError)) {
$emailTo = 'myemail#email.com'; //Put your own email address here
$body = "Name: $name \n\nEmail: $email \n\nSubject: $subject \n\nComments:\n $comments";
$headers = 'From: My Site <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;
mail($emailTo, $subject, $body, $headers);
$emailSent = true;
}
}
?>
The ereg() family of functions are deprecated. use the preg_...() equivalents instead. They work almost exactly the same, except requiring delimiters around the match patterns.
As well, don't use PHP_SELF in your form. That value is raw user-supplied data and can be trivially subverted for an XSS attack.
Checking for a particular form field to see if a POST occured is somewhat unreliable - you might change the field's name later on and your check will fail. However, this
if ($_SERVER['REQUEST_METHOD'] == 'POST) { ... }
will always work, no matter how many or few fields are in the form, as long as the form was actually POSTed.
As for the actual problem, I'm assuming the mail is getting sent out, or you'd have complained about that. That means your variables aren't being populated properly. Instead of just sending the mail, echo out the various variables as they're built, something like:
echo 'Checking name';
if ($_POST['name'] .....) {
echo 'name is blank';
} else {
$name = ...;
echo "Found name=$name";
}
Basically have your code become extremely "chatty" and tell you what it's doing at each stage.
#dafz: Change
if(isset($_POST['submit'])) {
to
if(isset($_POST['enviar'])) {
#Marc B deserves another up-vote for his answer as well.
Edit
You can try the following update.
if(!isset($hasError)) {
$siteAddress = 'validaddress#yourdomain.com'; //Put admin# or info# your domain here
$emailTo = 'myemail#email.com'; //Put your own email address here
$body = "Name: $name \r\nEmail: $email \r\nSubject: $subject \r\nComments: $comments \r\n";
$headers = 'To: ' . $name . ' <' . $emailTo . '>' . "\r\n";
$headers .= 'From: My Site <' . $siteAddress . '>' . "\r\n";
$headers .= 'Reply-To: ' . $email . "\r\n";
if (mail($emailTo, $subject, $body, $headers)) {
$emailSent = true;
} else {
$emailSent = false;
}
}

Categories