I'm using some php i found for sending a contact form from my site.
The HTML looks like this:
<div id="wrap">
<div id='form_wrap'>
<form id="contact-form" action="javascript:alert('success!');">
<p id="formstatus"></p>
<input type="text" name="name" value="" id="name" placeholder="Voornaam" required/>
<input type="text" name="email" value="" id="email" placeholder="E-mail adres" required/>
<textarea name="message" value="Your Message" id="message" placeholder="Uw vraag of projectomschrijving" required></textarea>
<input type="submit" name ="submit" value="Offerte aanvragen" />
</form>
</div>
</div>
The PHP looks like this:
<?php
define("WEBMASTER_EMAIL", 'your#emailadress.com');
error_reporting (E_ALL ^ E_NOTICE);
function ValidateEmail($email)
{
$regex = '/([a-z0-9_.-]+)'. # name
'#'. # at
'([a-z0-9.-]+){2,255}'. # domain & possibly subdomains
'.'. # period
'([a-z]+){2,10}/i'; # domain extension
if($email == '')
return false;
else
$eregi = preg_replace($regex, '', $email);
return empty($eregi) ? true : false;
}
$post = (!empty($_POST)) ? true : false;
if($post)
{
$name = stripslashes($_POST['name']);
$email = trim($_POST['email']);
$subject = stripslashes($_POST['subject']);
$message = stripslashes($_POST['message']);
$error = '';
// Check name
if(!$name || $name == "Name*")
$error .= 'Please enter your name.<br />';
// Check email
if(!$email || $email == "Email*")
$error .= 'Please enter an e-mail address.<br />';
if($email && !ValidateEmail($email))
$error .= 'Please enter a valid e-mail address.<br />';
// Check message
if(!$message)
$error .= "Please enter your message. <br />";
if(!$error)
{
$mail = mail(WEBMASTER_EMAIL, $subject, $message,
"From: ".$name." <".$email.">\r\n"
."Reply-To: ".$email."\r\n"
."X-Mailer: PHP/" . phpversion());
if($mail)
echo 'OK';
}
else
echo '<div class="formstatuserror">'.$error.'</div>';
}?>
It works great! BUT i need to add a few more INPUTS in my form. I know how to add those to the html. For instance I added this one:
<input type="text" name="lastname" value="" id="lastname" placeholder="Achternaam" required/>
But I just can't find the good way to add this input to the email that I receive in my mailbox... Where do I add this in the PHP? I tried lots of things...
Hope you guys can help me out!
David
After these lines:
$name = stripslashes($_POST['name']);
$email = trim($_POST['email']);
$subject = stripslashes($_POST['subject']);
$message = stripslashes($_POST['message']);
You instanciate a variable containing the value for your field (lastname):
$lastname = stripslashes($_POST['lastname']);
Then you validate your input if it's empty or something else:
// Check message
if(!$lastname )
$error .= "Please enter your lastname. <br />";
And finally, you use your variable lastname to display it on the email message:
"From: ".$name." ".$lasname." <".$email.">\r\n"
Et voilĂ !
EDIT: If you want to use this input on the message, you have the $message variable, and you can do so :
if(!$error)
{
$message .= "<p>Message sent by $lastname";
...
If you didn't want it going in the email headers as an addition to the 'From' or 'Subject', you could also keep appending information to the body of the email, or your $message. For example:
$name = stripslashes($_POST['name']);
$email = trim($_POST['email']);
$subject = stripslashes($_POST['subject']);
$message = "Last Name: " . stripslashes($_POST['lastname']) . "\r\n";
$message .= "Message: " . stripslashes($_POST['message']);
The other options work as well, it really just depends 'where' in the email you want this extra information going.
Related
I had/have the code below for users to send messages/emails from my website to my sites email address.
It was working fine, for weeks: Validating the field contents (if there was a blank 'required field', it asked for a "valid" field content i.e. email address), as long as there were no blank fields it was sending the email and was re-directing to the thank-you page - which acknowledges that the email has been sent.
Now, it has stopped working properly.
It doesn't seem to be validating (as it did originally) any more - as there are no warnings/errors for blank fields (if there is a blank field it simply doesn't send), it still sends the email to the address correctly (if there are no blank required fields), but it doesn't redirect to the thank-you page any more.
Here is the form code:
<form method="post" action="assets/sendmail.php">
<label for="name" class="nameLabel">Name</label>
<input id="name" type="text" name="name" placeholder="Enter your name...">
<label for="email" class="emailLabel">Email</label>
<input id="email" type="text" name="email" placeholder="Enter your email...">
<label for="subject">Subject</label>
<input id="subject" type="text" name="subject" placeholder="Your subject...">
<label for="message" class="messageLabel">Message</label>
<textarea id="message" name="message" placeholder="Your message..."></textarea>
<button type="submit">Send</button>
</form>
Here is the php code - note that I have substituted the email address for obvious reasons :)
<?php
// Email address verification
function isEmail($email) {
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", $email));
}
if($_POST) {
// Enter the email where you want to receive the message
$emailTo = 'me#myemail.com';
$clientName = trim($_POST['name']);
$clientEmail = trim($_POST['email']);
$subject = trim($_POST['subject']);
$message = trim($_POST['message']);
$array = array();
$array['nameMessage'] = '';
$array['emailMessage'] = '';
$array['messageMessage'] = '';
if($clientName == '') {
$array['nameMessage'] = 'Please enter your name.';
}
if(!isEmail($clientEmail)) {
$array['emailMessage'] = 'Please insert a valid email address.';
}
if($message == '') {
$array['messageMessage'] = 'Please enter your message.';
}
if($clientName != '' && isEmail($clientEmail) && $message != '') {
// Send email
$headers = "From: " . $clientName . " <" . $clientEmail . ">" . "\r\n" . "Reply-To: " . $clientEmail;
mail($emailTo, $subject, $message, $headers);
}
//echo json_encode($array);
{
header("location:../thankyou.html");
}
}
?>
Any help would be appreciated.
First of all, for email checking you can use built-in php as well.
filter_var($clientEmail, FILTER_VALIDATE_EMAIL)
I don't see where you output your errors so that may be why they are not showing,
I have added support for that
I have rewritten your code:
<?php
if (!empty($_POST)) {
// Enter the email where you want to receive the message
$emailTo = 'me#myemail.com';
$clientName = trim($_POST['name']);
$clientEmail = trim($_POST['email']);
$subject = trim($_POST['subject']);
$message = trim($_POST['message']);
$errors = array();
if (empty($clientName)) {
$errors['nameMessage'] = 'Please enter your name.';
}
if (!filter_var($clientEmail, FILTER_VALIDATE_EMAIL)) {
$errors['emailMessage'] = 'Please insert a valid email address.';
}
if (empty($message)) {
$errors['messageMessage'] = 'Please enter your message.';
}
// Are there errors?
if (count($errors) == 0) {
// Send email
$headers = "From: " . $clientName . " <" . $clientEmail . ">" . "\r\n" . "Reply-To: " . $clientEmail;
mail($emailTo, $subject, $message, $headers);
header("location:../thankyou.html");
} else {
foreach ($errors as $err) {
echo $err . '<br />';
}
}
}
?>
Thank-you for the updated PHP code. Unfortunately, it hasn't made any difference. It still sends the email when all fields are filled in, it even sends if the "subject" is empty, but it still does not re-direct to the thank-you page. It doesn't send if Name, Email Address, and Message are empty. But it does not display errors. I have tried to place both files in the parent directory and removing the assets/ from the action in the form and the ../ in the PHP. as below
<form method="post" action="sendmail.php">
<label for="name" class="nameLabel">Name</label>
<input id="name" type="text" name="name" placeholder="Enter your name...">
<label for="email" class="emailLabel">Email</label>
<input id="email" type="text" name="email" placeholder="Enter your email...">
<label for="subject">Subject</label>
<input id="subject" type="text" name="subject" placeholder="Your subject...">
<label for="message" class="messageLabel">Message</label>
<textarea id="message" name="message" placeholder="Your message..."></textarea>
<button type="submit">Send</button>
</form>
And the PHP is as you supplied (changing the email address of course)
<?php
if (!empty($_POST)) {
// Enter the email where you want to receive the message
$emailTo = 'me#myemail.com';
$clientName = trim($_POST['name']);
$clientEmail = trim($_POST['email']);
$subject = trim($_POST['subject']);
$message = trim($_POST['message']);
$errors = array();
if (empty($clientName)) {
$errors['nameMessage'] = 'Please enter your name.';
}
if (!filter_var($clientEmail, FILTER_VALIDATE_EMAIL)) {
$errors['emailMessage'] = 'Please insert a valid email address.';
}
if (empty($message)) {
$errors['messageMessage'] = 'Please enter your message.';
}
// Are there errors?
if (count($errors) == 0) {
// Send email
$headers = "From: " . $clientName . " <" . $clientEmail . ">" . "\r\n" . "Reply-To: " . $clientEmail;
mail($emailTo, $subject, $message, $headers);
header("location:thankyou.html");
} else {
foreach ($errors as $err) {
echo $err . '<br />';
}
}
}
?>
No Errors displayed if there are errors, no re-direct once sent. It just remains on the "contact" page and still displaying the completed form. Cannot understand why the re-direct was working but not now. Couldn't sign in when I posted this originally.
I am not very good with php and my friend helped me with this php contact form script. But this does not seem to send emails to the desired address. Can you please suggest what might be the problem with this script?
I really appreciate it. Thanks
<?php
$error = array();
if(!empty($_POST['contact_submit']) && ($_POST['contact_submit'] == 'submit') ) {
if(!empty($_POST['name'])) {
$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
} else {
$error[] = 'Please enter your name.';
}
if(!empty($_POST['email'])) {
if(filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
} else {
$error[] = 'Please enter a correct email address.';
}
} else {
$error[] = 'Please enter your email address.';
}
if(!empty($_POST['phone'])) {
if(filter_var($_POST['phone'], FILTER_VALIDATE_INT)) {
$phone = filter_var($_POST['phone'], FILTER_SANITIZE_NUMBER_INT);
} else {
$error[] = '<i>Phone number</i> only expects number';
}
} else {
$error[] = 'Please enter your email address.';
}
if(!empty($_POST['time'])) {
$time = filter_var($_POST['time'], FILTER_SANITIZE_STRING);
} else {
$error[] = 'Please enter your best time to contact.';
}
if(!empty($_POST['msg'])) {
$msg = filter_var($_POST['msg'], FILTER_SANITIZE_STRING);
} else {
$error[] = 'Please enter your message.';
}
if(empty($error)) {
$to = 'your#email.com';
$subject = 'from contact form';
$message = $phone . "\r\n";
$message .= $time . "\r\n";
$message .= $msg;
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= 'From: '.$name.' <'. $email.'>' . "\r\n" .
'Reply-To: '.$name.' <'. $email . '>' ."\r\n";
//echo '<pre>'; var_dump($to, $subject, $message, $headers); echo '</pre>'; die();
mail($to, $subject, $message, $headers);
}
}
?>
<?php
if(!empty($error)) {
echo '<ul class="error">';
echo '<li>' . implode('</li><li>', $error) . '</li>';
echo '</ul>';
}
?>
<form method="post" action="">
<input type="text" name="name" value="" placeholder="Enter your name" class="email_form"/>
<input type="text" name="email" value="" placeholder="Enter your email address" class="email_form"/>
<input type="text" name="phone" value="" placeholder="Phone number" class="email_form"/>
<input type="text" name="time" value="" placeholder="Best time to contact. e.g. 3 am" class="email_form"/>
<textarea name="msg" placeholder="Your message" class="email_form"></textarea>
<input type="image" value="submit" name="contact_submit" src="images/submit.png" width="96" height="43" class="email_button">
</form>
Change this line:
if(!empty($_POST['contact_submit']) && ($_POST['contact_submit'] == 'submit') ) {
to
if(isset($_POST['contact_submit']) ) {
and
<input type="image" value="submit" name="contact_submit" src="images/submit.png" width="96" height="43" class="email_button">
to
<input type = "submit" value="submit" name="contact_submit">
PHP is looking for a submit type, and you're using an image type.
If you still want to use the image as the submit button:
You will need to change:
if(!empty($_POST['contact_submit']) && ($_POST['contact_submit'] == 'submit') )
to another conditional statement.
For example:
if(!empty($_POST['email'])){
You can always add on to that conditional statement with the other fields you wish to check if they are set/empty.
For example:
if(!empty($_POST['email']) || !empty($_POST['name'])){
Upon testing your code, the code did not work till those changes were made.
N.B.: If mail is still not being sent/received, you will need to make sure that mail() is indeed available for you to use, and/or check your logs and the Spam box.
Add error reporting to the top of your file(s) which will help during production testing.
error_reporting(E_ALL);
ini_set('display_errors', 1);
Which will trigger any errors found.
Footnotes:
The phone field needs to be all numbers, otherwise it will fail.
I.e.: 555-234-5678 did not work, but 5552345678 did, therefore you will need to inform your users of how it should be entered.
Edit: (full code) - copy exactly as shown while changing email#example.com to your own Email.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
$error = array();
if(isset($_POST['contact_submit']) ) {
if(!empty($_POST['name'])) {
$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
} else {
$error[] = 'Please enter your name.';
}
if(!empty($_POST['email'])) {
if(filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
} else {
$error[] = 'Please enter a correct email address.';
}
} else {
$error[] = 'Please enter your email address.';
}
if(!empty($_POST['phone'])) {
if(filter_var($_POST['phone'], FILTER_VALIDATE_INT)) {
$phone = filter_var($_POST['phone'], FILTER_SANITIZE_NUMBER_INT);
} else {
$error[] = '<i>Phone number</i> only expects number';
}
} else {
$error[] = 'Please enter your email address.';
}
if(!empty($_POST['time'])) {
$time = filter_var($_POST['time'], FILTER_SANITIZE_STRING);
} else {
$error[] = 'Please enter your best time to contact.';
}
if(!empty($_POST['msg'])) {
$msg = filter_var($_POST['msg'], FILTER_SANITIZE_STRING);
} else {
$error[] = 'Please enter your message.';
}
if(empty($error)) {
$to = 'email#example.com';
$subject = 'from contact form';
$message = $phone . "\r\n";
$message .= $time . "\r\n";
$message .= $msg;
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= 'From: '.$name.' <'. $email.'>' . "\r\n" .
'Reply-To: '.$name.' <'. $email . '>' ."\r\n";
//echo '<pre>'; var_dump($to, $subject, $message, $headers); echo '</pre>'; die();
mail($to, $subject, $message, $headers);
}
}
?>
<?php
if(!empty($error)) {
echo '<ul class="error">';
echo '<li>' . implode('</li><li>', $error) . '</li>';
echo '</ul>';
}
?>
<form method="post" action="">
<input type="text" name="name" value="" placeholder="Enter your name" class="email_form"/>
<input type="text" name="email" value="" placeholder="Enter your email address" class="email_form"/>
<input type="text" name="phone" value="" placeholder="Phone number" class="email_form"/>
<input type="text" name="time" value="" placeholder="Best time to contact. e.g. 3 am" class="email_form"/>
<textarea name="msg" placeholder="Your message" class="email_form"></textarea>
<input type = "submit" value="submit" name="contact_submit">
</form>
You can also show a message if it was sent successfully by replacing:
mail($to, $subject, $message, $headers);
with:
if(mail($to, $subject, $message, $headers)){
echo "Mail sent, thank you.";
}
else{
echo "There was an error.";
}
You can also log the error:
http://php.net/manual/en/function.error-log.php
0 message is sent to PHP's system logger, using the Operating System's system logging mechanism or a file, depending on what the error_log configuration directive is set to. This is the default option.
1 message is sent by email to the address in the destination parameter. This is the only message type where the fourth parameter, extra_headers is used.
2 No longer an option.
3 message is appended to the file destination. A newline is not automatically added to the end of the message string.
4 message is sent directly to the SAPI logging handler.
I.e.:
if(mail($to, $subject, $message, $headers)){
echo "Mail sent, thank you.";
}
else{
error_log("Error!", 3, "/var/tmp/mail-errors.log");
}
I need a very simple, but effective PHP form handler that will work with this form:
<form id="contact" method="post" action="contact_handle.php">
<label for="name">Name:</label>
<input type="text" class="text_style" placeholder="John Doe" name="name" /><br />
<label for="email">Email:</label>
<input type="email" class="text_style" placeholder="email#example.com" name="email" /><br />
<label for="message">Subject:</label>
<textarea class="areawidth" rows="4" name="message" /></textarea><br />
<button id="contactbutton" type="submit">Submit</button>
</form>
This is what I currently have but it doesn't send an email and it doesn't redirect like I intended. And I cant seem to figure out whats going on.
<?php
$invalid = '';
$my_email = 'my#email.com';
// Validate input:
if(empty($_POST['name']) ||
empty($_POST['email']) ||
empty($_POST['message']))
{
$invalid.= "\n All fields are required";
}
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
// Validate email:
if (!preg_match(
"/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i",
$email))
{
$invalid .= "\n Invalid email address";
}
// Send email if no errors detected:
if( empty($invalid))
{
$to = $my_email;
$subject = "Contact form submission: $name";
$body = "You have received a new message. ".
" Here are the details:\n Name: $name \n ".
"Email: $email\n Message:\n $message";
$headers = "From: $email\n";
$headers .= "Reply-To: $email";
mail($to,$subject,$body,$headers);
//redirect to the thank you page:
header('Location: contact_thanks.php');
}
?>
When it is submitted it takes me to contact_handle.php that displays blank and fails to redirect.
i think the redirect has to be the first output to the browser, so if anything else is being output it won't work.
why don't you just include the thank you page rather than redirecting to it, ie.
include 'contact_thanks.php';
If you're providing all of the code, the issue is that your form is throwing an error (by adding text to $invalid, but there is no code to handle $invalid not being empty. To solve this, add this after the closing } at the end:
echo $invalid;
It seems everything is in place:
PHP:
<?php
if (!empty($_POST['name'])){
$msg = "name". $_POST['name'];
}else{
$fname = NULL;
echo "Name Required.<br />";
}
if (!empty($_POST['email'])){
$msg = "email". $_POST['email'];
}else{
$lname = NULL;
echo "Email Required.<br />";
}
if (!empty($_POST['www'])){
$msg = "Website". $_POST['www'];
}else{
$lname = NULL;
echo "Website Required.<br />";
}
if (!empty($_POST['comment'])){
$msg = "Comment". $_POST['comment'];
}else{
$email = NULL;
echo "A comment is required.<br />";
}
$recipient = "myemail#gmail.com";
$subject = "Form Feedback";
$mailheaders = "Reply-to". $_POST['email'];
//send the mail
mail($recipient, $subject, $msg, $mailheaders);
?>
HTML:
<div id="contact" style="height:280px; margin:1px 0;">
<form id="contactLP" method="post" action="inc/php/contact_validate.php">
<div class="align"><input type="text" name="name" tabindex="1" /></div>
<div class="align"><input type="text" name="email" tabindex="2" /></div>
<div class="align"><input type="text" name="www" tabindex="3" /></div>
<div class="align"><textarea id="txta" name="comment" cols="15" rows="5" tabindex="4"></textarea></div>
<span style="color:transparent;">test</span>
<br><br>
<div class="align"><input type="submit" class="submit" name="sendForm" id="SubmitContact" value="" tabindex="5" /></div>
</form>
</div><!--CONTACT-->
When I fill it out correctly and submit, it says "Thanks for your message" or something similiar, but then I get nothing in email.
I tried running this both on a server on the internet, along with on my local server running on my workstation.
Am I doing something wrong above???????
Yes, you are "name; $_POST['name'] "; should be "name". $_POST['name']; in every instance you use that string.
Your $msg is only holding the current value.
Try something like this for all your value assignment to $msg variable
$msg .= "Comment". $_POST['comment'];
mail function
You seem to have screwed up the $mailheaders variable slightly (reply-to section), try this code in a stand alone script. If even it fails, you may have to check your mail function and how it is set up on the server. (change the email addresses obviously)
<?php
$to = 'nobody#example.com';
$subject = 'the subject';
$message = 'hello';
$headers = 'From: webmaster#example.com' . "\r\n" .
'Reply-To: webmaster#example.com';
mail($to, $subject, $message, $headers);
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;
}
}