PHP email script not working after validation - php

There must be thousands of questions asked about PHP email scripts but I still haven't found my answer. I looked on the php website but it didn't really help either.
Basically my script validates the inputs and displays error message accordingly but when I add the second part of the script to handle the sending of the email the page displays a 500 error. Here is my code. The email hasn't been set to the correct email at the moment but I know that's not the problem.
<?php include('includes/header.php');
$yourEmail = "hello#example.com";
$formSubject = "Message recieved from enquiry form";
if( isset( $_POST["submit"])) {
//Validate the data
function validateFormData( $formData ) {
$formData = trim( stripslashes(htmlspecialchars( $formData )));
return $formData;
}
//check to see if inputs are empty
// create variables with form data
// wrap the data with our function
if( !$_POST['name']) {
$nameError = "Please enter your name <br />";
} else {
$name = validateFormData( $_POST["name"]);
}
if( !$_POST['email'] || !preg_match("/^\S+#\S+$/", $email)) {
$emailError = "Please enter a valid email address <br />";
} else {
$email = validateFormData( $_POST["email"]);
}
if( !$_POST['enquiry']) {
$enquiryError = "Please enter your enquiry <br />";
} else {
$enquiry = validateFormData( $_POST["enquiry"]);
}
Code Works fine up until this point;
//Check to see if submit is set
//Check to make sure errors don't exist
//Send the email
// Redirect user to success.html
if ( isset( $_POST["submit"]) && (empty($emailError, $nameError, $enquiryError))) {
$to = $yourEmail;
$subject = $formSubject;
$headers = 'From:'. $name . "\r\n".
'Reply-To: '. $email . "\r\n".
'X-Mailer: PHP/' . phpversion();
$body =
'The person that contacted you was '.$name.'
Email: '.$email.'
URL: '.$url.'
Message: '.$enquiry.''.
mail($yourEmail, $formSubject, $body, $headers);
header("Location: success.html");
}
}
?>
This is the HTML form, which I'm sure is alright considering the PHP works up until a certain point and displays the error messages correctly. I know I have PHP_SELF which a lot of people say not to use but I want to to stay on the page if errors exist and only redirect if email has sent.
<form id="contactForm" method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<label for="name">Name <span class="asterisk">*</span></label>
<input type="text" name="name" id="name" value="<?php echo $name;?>"tabindex="1"/>
<span class="error"><?php echo $nameError; ?></span>
<label for="email">Email <span class="asterisk">*</span></label>
<input type="email" name="email" id="email" value="<?php echo $email;?>" tabindex="2"/>
<span class="error"><?php echo $emailError; ?></span>
<span class="error"><?php echo $emailValidError; ?></span>
<label for="url">Website</label>
<input type="url" name="url" id="url" value="<?php echo $url;?>" tabindex="3"/>
<h3>Tell us about your project </h3><br />
<textarea name="enquiry" id="enquiry" tabindex="4"><?php echo $enquiry;?></textarea>
<span class="error"><?php echo $enquiryError; ?></span>
<button type="submit" id="submit" name="submit" value="submit" >Submit</button>
</form>

Your problem is here:
empty($emailError, $nameError, $enquiryError)
empty accepts only one param, you are passing it 3. Change the conditional to:
if( isset( $_POST["submit"]) && ( empty($emailError) && empty($nameError) && empty($enquiryError) ))
Or if you want to shorten that conditional a little
$Errors = $emailError.$nameError.$enquiryError;
if( isset( $_POST["submit"] ) && empty( $Errors ) )

This is why there's an error. First syntax error and then (empty($emailError, $nameError, $enquiryError)) is not a good idea. I would do something like this:
$err=0;
if( !$_POST['name']) {
$nameError = "Please enter your name <br />";
$err++;
} else {
$name = validateFormData( $_POST["name"]);
$err++;
}
if( !$_POST['email'] || !preg_match("/^\S+#\S+$/", $email)) {
$emailError = "Please enter a valid email address <br />";
$err++;
} else {
$email = validateFormData( $_POST["email"]);
}
if( !$_POST['enquiry']) {
$enquiryError = "Please enter your enquiry <br />";
$err++;
} else {
$enquiry = validateFormData( $_POST["enquiry"]);
}
if ( isset( $_POST["submit"]) && $err==0) {
//your code here//
//and i would do like this//
$result_mail_send = mail($yourEmail, $formSubject, $body, $headers);
if($result_mail_send==true){
//redirect to success
}else{
//redirect to fail//
}
}

Related

Form not showing?

I require some assistance that I hope that one of you can answer for me. I have an assignment for my PHP course. For this assignment we were tasked with making a form with 4 input fields (including a reset and submit button). The fields are supposed to be labeled as name, address, email, and phone number. Now when I write the code into Dreamweaver I get no syntax errors but whenever I execute the script using Wamp, the form doesn't show. Any help would be appreciated as this is something that has to be done for our midterm.
<?php
function validateInput($data, $fieldName) {
global $errorCount;
if (empty($data)) {
echo "\"$fieldName\" is a required field. <br />\n";
++$errorCount;
$retval = "";
} else { //Only clean up the input if it isn't // empty
$retval = trim($data);
$retval = stripslashes($retval);
}
return($retval);
}
function validateEmail ($data, $fieldName) {
global $errorCount;
if (empty($data)) {
echo "\"$fieldName\" is a required field.<br />\n";
++$errorCount;
$retval = "";
} else { // Only Clean up the input if it isn't // empty
$retval = trim($data);
$retval = stripslashes($retval);
$pattern = "/^[\w-]+(\.[\w-]+)*#" .
"[\w-]+(\.[\w-]+)*" .
"(\. [[a-z]]{2,})$/i";
if (preg_match($pattern, $retval)==0) {
echo "\"$fieldName\" is not a valid e-mail address.<br />\n";
++$errorCount;
}
}
return($retval);
}
function displayForm($Sender, $Email, $Address, $Phone) {
?>
<h2 style= "text-align:center">Contact Us</h2>
<form name="contact" action="contact_us.php" method="post">
<p>Your Name: <input type="text" name="Sender" value="<?php
echo $Sender; ?>" /> </p>
<p>Your E-mail: <input type="text" name="Email" value="<?php echo $Email; ?>" /></p>
<p>Address: <input type="text" name="Address" value="<?php echo $Address; ?>" /></p>
<p>Phone #: <input type="number" name="Phone" value="<?php echo $Phone; ?>"<br />
</p>
<p><input type="reset" value="Clear Form" /> <input type="submit" name="Submit" value="Send Form" /></p>
</form>
<?php
}
$ShowForm = TRUE;
$errorCount = 0;
$Sender = "";
$Email = "";
$Address = "";
$Phone = "";
if (isset($_POST['Submit'])) {
$Sender =
validateInput($_POST['Sender'], "Your Name");
$Email =
validateEmail($_POST['Email'], "Your E-mail");
$Subject =
validateInput($_POST['Address'], "Your Address");
$Message =
validateInput($_POST['Phone'],"Your number");
if ($errorCount==0)
$ShowForm = FALSE;
else
$ShowForm = TRUE;
}
if ($ShowForm == TRUE) {
if ($errorCount>0) // if there were errors echo "<p>Please re-enter the form information below.</p>\n";
displayForm($Sender, $Email, $Address, $Phone);
}
else {
$SenderAddress= "$Sender <$Email>";
$Headers= "From: $SenderAddress\nCC:
$SenderAddress\n";
// Substitute your own email address for // recipient#example.com
$result = mail ("recipient#example.com",
$Subject, $Message, $Headers);
if ($result)
echo "<p>Your message has been sent. Thank you, " . $Sender . ".</p>\n";
else
echo "<p>There was an error sending your message, " .
$Sender . ".</p>\n";
} ?>
You see nothing becouse you din`t call the function displayForm() you just create it.
so put this displayForm(); before the end of your php tag and see what will happen.
if ($ShowForm == TRUE) {
if ($errorCount>0) // if there were errors echo "<p>Please re-enter the form information below.</p>\n";
displayForm($Sender, $Email, $Address, $Phone);
}
It looks like your form is set to only show when $ShowForm == TRUE && $errorCount > 0. Since your defaults are $ShowForm = TRUE and $errorCount = 0 your form will never show.
This is why using curly braces on your ifs, while making the file larger, help greatly when troubleshooting.

PHP, trying to add captcha to existing form

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>

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;

PHP form takes back to top

I have PHP included a PHP form in my portfolio, that you can see here http://www.tinybigstudio.com The thing is that after SUBMIT, the page goes to TOP instead of staying at the bottom where the form is.
This is the PHP code I have:
<?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 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 = 'info#tinybigstudio.com'; //Put your own email address here
$body = "Name: $name \n\nEmail: $email \n\nComments:\n $comments";
$headers = 'From: My Site <'.$emailTo.'>' .$subject = "You have mail, yes!" . "\r\n" . 'Te lo manda: ' . $name;
mail($emailTo, $subject, $body, $headers);
$emailSent = true;
}
}
?>
And this is the form:
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" id="contactform">
<fieldset>
<label for="name">Name</label>
<input type="text" size="50" name="contactname" id="contactname" value="" class="required">
<label for="email">Email</label>
<input type="text" size="50" name="email" id="email" value="" class="required">
<label for="message">Message</label>
<textarea rows="5" cols="50" name="message" id="message" class="required"></textarea>
<input type="submit" value="S E N D" class="send" name="submit" onmouseover="this.className='send_hover';"
onmouseout="this.className='send';">
</form>
<?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>Message Successfully Sent!</strong></p>
<p>Thank you <strong><?php echo $name;?></strong> for sending a message!</p>
<?php }
?>
you need to add an anchor to the contact form and use this as the form action.eg:
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>#contact" >
and add this 'pseudo-link' right before the contact form
<a name="contact">Contact me</a>
Now after submit user will be send to the form directly and not the top of the page
This is because you are submitting it to the same page that you are on, therefore the browser goes effectively refreshes with the $_POST data. If you want to stop this you need to use AJAX to submit it so that it happens in the background. Take a look at the API - http://api.jquery.com/jQuery.ajax/

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