echo an error message for each input in form - php

i have a form with input for name and e-mail. I would like to have a dedicated error-message for each input - fx
if no name is written it will say "please write your name!"
and if the e-mail is missing or not valid it echoes "wrong mail - try again!"
At the moment I have only 1 error-message that will echo for both situations.
How can i assign an dedicated error-message for each of the inputs?
Heres the code:
<?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']);
}
//If there is no error, send the email
if(!isset($hasError)) {
$emailTo = '##gmail.com'; //Put your own email address here
$body = "Name: $name \n\nEmail: $email \n\nComments:\n $comments";
$headers = 'From: My Site <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;
mail($emailTo, $subject, $body, $headers);
$emailSent = true;
}
}
?>
<article class="kontakt">
<?php if($_POST['contactname'] != '') { //echo when a name was entered ?>
<!--<p> Hello </p>-->
<?php $name = strip_tags(trim($_POST['contactname']));
echo $name;
} ?>
</article>
<article class="kontakt">
<?php if(isset($hasError)) { // THIS PART IS ECHOED IN BOTH SITUATIONS - should only apply for error in e-mail?>
<p class="error"> Your mail is <span style="color: orange"> not correct</span> - try again! </p>
<?php } ?>
<?php if($_POST['email'] != '') { // echo when a valid mail was entered ?>
<p> Hello </p>
<?php $name = strip_tags(trim($_POST['email']));
echo $email;
} ?>
</article>
<article class="kontakt">
<?php if(isset($emailSent) && $emailSent == true) { //If email is sent ?>
<p> Your message is sent !</p>
<?php } ?>
</article>
}
?>

try something like:
if(trim($_POST['contactname']) == '') {
$hasError['contactname'] = 'Please enter a contact name!';
} else {
$name = trim($_POST['contactname']);
}
//Check to make sure sure that a valid email address is submitted
if(trim($_POST['email']) == '') {
$hasError['email'] = 'Please enter email!';
} else if (!eregi("^[A-Z0-9._%-]+#[A-Z0-9._%-]+\.[A-Z]{2,4}$", trim($_POST['email']))) {
$hasError['validemail'] = 'Please enter valid email';
} else {
$email = trim($_POST['email']);
}
and this to display errors:
if(isset($hasError)){
echo '<ul>';
foreach($hasError as $error){
echo '<li>'.$error.'</li>';
}
echo '</ul>';
}
and this to keep old values upon error
<div class="right_wrap">
<div class="header"> <h5><span style="color: white"> mail </span></h5> </div>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" id="contactform">
<article class="kontakt">
<label for="name"> Dit navn </label>
<input type="text" name="contactname" id="contactname" value="<?php echo $_POST['contactname']; ?>" class="" />
</article>
<article class="kontakt">
<label for="email"> Din mail </label>
<input type="text" name="email" id="email" value="<?php echo $_POST['email']; ?>" class="required email" />
</article>
<article class="kontakt" style="height: auto">
<label for="message"> Din besked </label>
<textarea rows="5" cols="50" name="message" class="required"><?php echo $_POST['message']; ?></textarea>
</article>
<article class="kontakt">
<input type="submit" value="Send besked" name="submit" class="button"/>
</article>
</form>
</div> <!--end of right_wrap -->

You treat each input with individual code that means you don't have much data-structure here.
Normally some kind of model for inputs as well as associated errors and values is helpful to get things done with forms.
A lightweight entry that normally works pretty well with individual PHP scripts is HTML_QuickForm2.
It does take care of individual error messages as well. You naturally can write that your own and luckily it is free software so you are allowed to study the code and learn from it.

Heres the actual form - some danish words in it. Whatever errors / messages will be output in a left wrap div - so cant be placed inside the actual form.
<div class="right_wrap">
<div class="header"> <h5><span style="color: white"> mail </span></h5> </div>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" id="contactform">
<article class="kontakt">
<label for="name"> Dit navn </label>
<input type="text" name="contactname" id="contactname" value="" class="" />
</article>
<article class="kontakt">
<label for="email"> Din mail </label>
<input type="text" name="email" id="email" value="" class="required email" />
</article>
<article class="kontakt" style="height: auto">
<label for="message"> Din besked </label>
<textarea rows="5" cols="50" name="message" class="required"></textarea>
</article>
<article class="kontakt">
<input type="submit" value="Send besked" name="submit" class="button"/>
</article>
</form>
</div> <!--end of right_wrap -->

Related

Email wont send with information entered and sends blank email on page refresh

I have done server side validation for my contact form and when the user fails to enter information into a required field an error occurs when the send button is pressed and no email is sent. I can't get the email to send if all the relevant information is input into the fields. The form is validated and sent on the same page. I have added the right script to send the email but on page refresh it sends a blank email and shows no errors.
<?php
// define variables and set to empty values
$firstnameErr = $secondnameErr = $emailaddressErr = $commentErr = $captchaErr = "";
$firstname = $email = $secondname = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["firstname"])) {
$firstnameErr = "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)) {
$firstnameErr = "Invalid first name";
}
}
if (empty($_POST["secondname"])) {
$secondnameErr = "Second name is required";
} else {
$secondname = test_input($_POST["secondname"]);
// check if e-mail address syntax is valid
if (!preg_match("/^[a-zA-Z ]*$/",$secondname)) {
$secondnameErr = "Invalid second name";
}
}
if (empty($_POST["emailaddress"])) {
$emailaddressErr = "Email address is required";
} else {
$emailaddress = test_input($_POST["emailaddress"]);
// check if e-mail address syntax is valid
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$emailaddress)) {
$emailaddressErr = "Invalid email format";
}
}
if (empty($_POST["comment"])) {
$commentErr = "Enter a message";
} else {
$comment = test_input($_POST["comment"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$comment)) {
$commentErr = "Only letters and white space allowed";
}
}
if (empty($_POST["captcha"])) {
$captchaErr = "Enter the answer to the sum";
} else {
$captcha = test_input($_POST["captcha"]);
// check if name only contains letters and whitespace
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<form name="Contact" form id="Contact" onsubmit=" return validate()" METHOD="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div class="Row">
<div class="Lable">First Name:</div> <!--End of Lable-->
<div class="input">
<input type="text" id="firstname" class="detail" name="firstname" placeholder="First Name" />
<span class="error"><?php echo $firstnameErr;?></span> </div>
<!--End input-->
</div> <!--End row--><br />
<div class="Row">
<div class="Lable">Second Name:</div> <!--End of Lable-->
<div class="input">
<input type="text" id="secondname" class="detail" name="secondname" placeholder="Second Name" />
<span class="error"><?php echo $secondnameErr;?></span> </div>
<!--End input-->
</div> <!--End row-->
<br />
<div class="Row">
<div class="Lable">Email Address:</div> <!--End of Lable-->
<div class="input">
<input type="email" id="emailaddress" class="detail" name="emailaddress" placeholder="Email Address" />
<span class="error"><?php echo $emailaddressErr;?></span>
</div> <!--End input-->
</div> <!--End row-->
<br />
<div class="Row">
<div class="Lable">Your Message:</div> <!--End of Lable-->
<div class="input">
<textarea id="comment" name="comment" class="mess" placeholder="Your Message" minlength="10" ></textarea>
<span class="error"><?php echo $commentErr;?></span>
</div> <!--End input-->
</div> <!--End row-->
<br />
<input id="number1" name="number1" readonly="readonly" class="Add" value="<?php echo rand(1,4) ?>" /> +
<input id="number2" name="number2" readonly="readonly" class="Add" value="<?php echo rand(5,9) ?>" /> =
<input type="text" name="captcha" id="captcha" class="captcha" maxlength="2" />
<div class="Lable">Please give the correct answer to the sum</div>
<br />
<span class="captchaerror"><?php echo $captchaErr;?></span>
<br />
<br />
<div class="submit">
<input type="submit" id="send" Name="send" value="Send" />
</div><!--End of submit-->
<div class="Clear">
<input type="reset" id="clear" Name="Clear" value="Clear" />
</div>
</form>
<?php
if (!empty($_POST)) {
}
else {
$firstname = $_POST["firstname"];
$secondname = $_POST["secondname"];
$email = $_POST["emailaddress"];
$comments = $_POST["comment"];
$message = "New Email for a customer" .
"\r\nName of the contact" .
"\r\n-". $firstname .
"\r\nName of the contact" .
"\r\n-". $secondname .
"\r\nEmail address of the contact" .
"\r\n-".$email .
"\r\nThe comment that the contact has made" .
"\r\n-".$comments .
$headers = "From: " . $email;
mail("kieran#localhost",$subject,$message,$headers);
$subjectReply = 'Thank you for your contact..';
$messageReply = 'You will soon receive an answer';
$headers = 'From: admin#shreddednutrition';
mail($email, $subjectReply, $messageReply, $headers);
}
?>
thanks in advance
Why:
if (!empty($_POST)) {
}
else {
so basically the code does nothing if there is some $_POST data..
Change to:
if (empty($_POST)) {
}
else {

PHP contact form will not submit

I have a simple php contact form i got from a web tutorial. It worked yesterday, but will not work today. I'd love some help, as I don;t know much php.
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 (!filter_var( trim($_POST['email'], FILTER_VALIDATE_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 = 'person#domain.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;
}
}
?>
HTML:
<form role="form" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" id="contactform">
<?php if(isset($hasError)) { //If errors are found ?>
<p class="alert alert-danger">Please check if you've filled all the fields with valid information and try again. Thank you.</p>
<?php } ?>
<?php if(isset($emailSent) && $emailSent == true) { //If email is sent ?>
<div class="alert alert-success">
<p><strong>Message Successfully Sent!</strong></p>
<p>Thank you for using our contact form, <strong><?php echo $name;?></strong>! Your email was successfully sent and we’ll be in touch with you soon.</p>
</div>
<?php } ?>
<div class="form-group">
<label for="name">Your Name<span class="help-required">*</span></label>
<input type="text" name="contactname" id="contactname" value="" class="form-control required" role="input" aria-required="true" />
</div>
<div class="form-group">
<label for="email">Your Email<span class="help-required">*</span></label>
<input type="text" name="email" id="email" value="" class="form-control required email" role="input" aria-required="true" />
</div>
<div class="form-group">
<label for="subject">Subject<span class="help-required">*</span></label>
<input type="text" name="email" id="subject" class="form-control required" role="input" aria-required="true">
</div>
<div class="form-group">
<label for="message">Message<span class="help-required">*</span></label>
<textarea rows="8" name="message" id="message" class="form-control required" role="textbox" aria-required="true"></textarea>
</div>
<div class="actions">
<input type="submit" value="Send Your Message" name="submit" id="submitButton" class="btn btn-grey" title="Click here to submit your message!" />
<input type="reset" value="Clear Form" class="btn btn-grey pull-right" title="Remove all the data from the form." />
</div>
</form>
It gets hung up on the validation. Not sure why.
$_POST["subject] is not defined in your form. Your SUBJECT field is called EMAIL:
Change:
<div class="form-group">
<label for="subject">Subject<span class="help-required">*</span></label>
<input type="text" name="email" id="subject" class="form-control required" role="input" aria-required="true">
</div>
With:
<div class="form-group">
<label for="subject">Subject<span class="help-required">*</span></label>
<input type="text" name="subject" id="subject" class="form-control required" role="input" aria-required="true">
</div>

Hide or clear a PHP form on submit

I have a php contact form which all works well with its validation etc, but I have one niggle with it. The original code which I have tweaked redirected the page to a new one with a thank you message on submission which I was unhappy with, so I've managed to get a thank you message to display on the original page, however the input form content still stays, i'd rather it didn't. Even better I'd like to be able to hide the form completely and replace it with a thank you.
I ought to mention that when completed it will be placed on a page with other items, so it is just the form that I'm after hiding, or clearing.
This is the code in the Header
<?php
$your_email ='email#example.com';
session_start();
$errors = '';
$name = '';
$company = '';
$visitor_email = '';
$phone = '';
$user_message = '';
if(isset($_POST['submit']))
{
$name = $_POST['name'];
$company = $_POST['company'];
$visitor_email = $_POST['email'];
$phone = $_POST['phone'];
$user_message = $_POST['message'];
///------------Do Validations-------------
if(empty($name)||empty($visitor_email))
{
$errors .= "\n Name and Email are required fields. ";
}
if(IsInjected($visitor_email))
{
$errors .= "\n Bad email value!";
}
if(empty($_SESSION['6_letters_code'] ) ||
strcasecmp($_SESSION['6_letters_code'], $_POST['6_letters_code']) != 0)
{
//Note: the captcha code is compared case insensitively.
//if you want case sensitive match, update the check above to
// strcmp()
$errors .= "\n The captcha code does not match!";
}
if(empty($errors))
{
//send the email
$to = $your_email;
$subject="New form submission";
$from = $your_email;
$ip = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '';
$body = "A user $name submitted the contact form:\n".
"Name: $name\n".
"Company: $company\n".
"Email: $visitor_email \n".
"Phone: $phone\n".
"Message: \n ".
"$user_message\n".
"IP: $ip\n";
$headers = "From: $from \r\n";
$headers .= "Reply-To: $visitor_email \r\n";
mail($to, $subject, $body,$headers);
//header('Location: #thanks');
$myForm = '< style="visibility: hidden;">';
$thankyou = file_get_contents("thank-you.html");
}
}
// Function to validate against any email injection attempts
function IsInjected($str)
{
$injections = array('(\n+)',
'(\r+)',
'(\t+)',
'(%0A+)',
'(%0D+)',
'(%08+)',
'(%09+)'
);
$inject = join('|', $injections);
$inject = "/$inject/i";
if(preg_match($inject,$str))
{
return true;
}
else
{
return false;
}
}
?>
And this is the form itself minus a chunk of javascript validation which I didn't think was relevant to the question
<?php
if(!empty($errors)){
echo "<p class='err'>".nl2br($errors)."</p>";
}
?>
<div id="footer">
<div class="twelve-column-wrapper">
<div class="six-column-wrapper">
<div class="six-column">
<h3>Why not get in touch</h3>
</div>
<div id='contact_form_errorloc' class='err'></div>
<form method="POST" name="contact_form"
action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>">
<div class="three-column">
<p>
<label for='name'>Name: </label>
<br>
<input type="text" name="name" value='<?php echo htmlentities($name) ?>'>
</p>
</div>
<div class="three-column">
<p>
<label for='company'>Your Company: </label>
<input type="text" name="company" id="company" value='<?php echo htmlentities($company) ?>'/>
</p>
</div>
<div class="three-column">
<p>
<label for='email'>Email: </label>
<br>
<input type="text" name="email" value='<?php echo htmlentities($visitor_email) ?>'>
</p>
</div>
<div class="three-column">
<p>
<label for='phone'>Phone No. </label>
<input type="text" name="phone" id="phone" value='<?php echo htmlentities($phone) ?>'/>
</p>
</div>
<div class="six-column">
<p>
<label for='message'>Message:</label>
<br>
<textarea name="message" rows=8 cols=30><?php echo htmlentities($user_message) ?></textarea>
</p>
</div>
<div class="three-column">
<p> <img src="captcha_code_file.php?rand=<?php echo rand(); ?>" id='captchaimg' ><br>
<label for='message'>Enter the code above here :</label>
<br>
<input id="6_letters_code" name="6_letters_code" type="text">
<br>
<small>Can't read the image? click <a href='javascript: refreshCaptcha();'>here</a> to refresh</small> </p>
<input id="submit" type="submit" value="Submit" name='submit'>
</div>
<div class="six-column"> <?php echo $thankyou; ?> </div>
</form>
</div>
</div>
</div>
I have tried a few methods I've found by searching but have fallen down mainly due to my basic knowledge of PHP.
Any help would be much appreciated.
<?php
if(!empty($errors)){
echo "<p class='err'>".nl2br($errors)."</p>";
}
?>
<div id="footer">
<div class="twelve-column-wrapper">
<div class="six-column-wrapper">
<div class="six-column">
<h3>Why not get in touch</h3>
</div>
<div id='contact_form_errorloc' class='err'></div>
<?php
if(!isset($_POST['submit'])):
?>
<form method="POST" name="contact_form"
action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>">
<div class="three-column">
<p>
<label for='name'>Name: </label>
<br>
<input type="text" name="name" value='<?php echo htmlentities($name) ?>'>
</p>
</div>
<div class="three-column">
<p>
<label for='company'>Your Company: </label>
<input type="text" name="company" id="company" value='<?php echo htmlentities($company) ?>'/>
</p>
</div>
<div class="three-column">
<p>
<label for='email'>Email: </label>
<br>
<input type="text" name="email" value='<?php echo htmlentities($visitor_email) ?>'>
</p>
</div>
<div class="three-column">
<p>
<label for='phone'>Phone No. </label>
<input type="text" name="phone" id="phone" value='<?php echo htmlentities($phone) ?>'/>
</p>
</div>
<div class="six-column">
<p>
<label for='message'>Message:</label>
<br>
<textarea name="message" rows=8 cols=30><?php echo htmlentities($user_message) ?></textarea>
</p>
</div>
<div class="three-column">
<p> <img src="captcha_code_file.php?rand=<?php echo rand(); ?>" id='captchaimg' ><br>
<label for='message'>Enter the code above here :</label>
<br>
<input id="6_letters_code" name="6_letters_code" type="text">
<br>
<small>Can't read the image? click <a href='javascript: refreshCaptcha();'>here</a> to refresh</small> </p>
<input id="submit" type="submit" value="Submit" name='submit'>
</div>
</form>
<?php
endif;
?>
<div class="six-column"> <?php echo $thankyou; ?> </div>
</div>
</div>
</div>
That will hide the form. But that won't prevent you to be spammed. If you don't want to be spammed to have to track IPs and before submitting the email check that the IP didn't already send an email let's say in the last 30 seconds, for instance.
if(empty($_POST)){
//You form goes here;
}
else{
echo $thankyou;
}
Also you can have something like:
if(empty($thankyou)){
//You form goes here;
}
else{
echo $thankyou;
}
You can trigger this function onsubmit or onclick event on form
<script>
function hideform()
{
document.forms['contact_form'].style.visibility = 'hidden';
}
</script>
You could use jQuery to clear the form div on a successful submission.
$('#myform').submit(function(){
$('#formcontainer').empty;
});
Where myform and form container are the ids of your form and the div containing your form
You better create separate action file and for display thanks message use:
if(isset($_SESSION['msg'])){
echo $_SESSION['msg'];
}
else{
//display from here
}

Contact Form: Why won't this form validate?

I have a contact form at the bottom of a, (single page business/portfolio), website.
The script above my DOCTYPE looks like this.
<?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['comment']) == '') {
$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#gmail.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 JQuery validation does work.
<script type="text/javascript">
$(document).ready(function(){
$("form").validate();
});
</script>
The contact form:
<div class="grid_8">
<?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 using my contact form! Your email was successfully sent and I will be in touch with you soon.</p>
<?php } ?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<div>
<label for="name">Your Name:</label>
<div>
<input type="text" name="contactname" class="required" />
</div>
</div>
<div>
<label for="email">Your Email:</label>
<div>
<input type="text" name="email" class="required email" />
</div>
</div>
<div>
<label for="subject">Subject:</label>
<div>
<input type="text" name="subject" class="required" />
</div>
</div>
<div>
<label for="comments">Comments:</label>
<div>
<textarea name="comment" name="comment" class="required"></textarea>
</div>
</div>
<div>
<input id="button" type="submit" value="SEND" />
</div>
</form>
</div>
When you submit the form, the email does not get sent, nor any verification from php. What am I doing wrong?
One quick obvious issue, although I have many less critical ones. Simply put you'r checking for $_POST['submit'] put there is name="submit" in your form.
So change:
<input id="button" type="submit" value="SEND" />
To:
<input id="button" type="submit" name="submit" value="SEND" />
Or change:
if(isset($_POST['submit']))
To:
if(count($_POST))
// OR
if(!empty($_POST))
Either one will fix your problem
I don't see why isset($_POST['submit']) should return true when you have no field with name="submit" in your form.
What I prefer to do is using an array for all the required data:
<!-- ... -->
<input type="text" name="mail[contactname]" class="required" />
<!-- ... -->
<input type="text" name="mail[email]" class="required email" />
<!-- ... -->
<input type="text" name="mail[subject]" class="required" />
<!-- ... -->
<textarea name="comment" name="mail[comment]" class="required"></textarea>
<!-- ... -->
And then asking for that array
if (isset($_POST['mail']))
// ...

add fields to contact.php

I got a template online... They included this contact.php - And how do I add extra fields so this contact.php will send it to me.
<?php
if(!$_POST) exit;
$email = $_POST['email'];
//$error[] = preg_match('/\b[A-Z0-9._%-]+#[A-Z0-9.-]+\.[A-Z]{2,4}\b/i', $_POST['email']) ? '' : 'INVALID EMAIL ADDRESS';
if(!eregi("^[a-z0-9]+([_\\.-][a-z0-9]+)*" ."#"."([a-z0-9]+([\.-][a-z0-9]+)*)+"."\\.[a-z]{2,}"."$",$email )){
$error.="Invalid email address entered";
$errors=1;
}
if($errors==1) echo $error;
else{
$values = array ('name','email','message');
$required = array('name','email','message');
$your_email = "myemail#live.ca";
$email_subject = "New Message: ".$_POST['subject'];
$email_content = "new message:\n";
foreach($values as $key => $value){
if(in_array($value,$required)){
if ($key != 'subject' && $key != 'company') { if( empty($_POST[$value]) ) { echo 'PLEASE FILL IN REQUIRED FIELDS'; exit; }
}
$email_content .= $value.': '.$_POST[$value]."\n";
}
}
if(#mail($your_email,$email_subject,$email_content)) {
echo 'Message sent!';
} else {
echo 'ERROR!';
}
}
?>
The HTML contact page is:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link href="style.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
// <![CDATA[
jQuery(document).ready(function(){
$('#contactform').submit(function(){
var action = $(this).attr('action');
$.post(action, {
name: $('#name').val(),
email: $('#email').val(),
telephone: $('#telephone').val(),
company: $('#company').val(),
subject: $('#subject').val(),
message: $('#message').val()
},
function(data){
$('#contactform #submit').attr('disabled','');
$('.response').remove();
$('#contactform').before('<p class="response">'+data+'</p>');
$('.response').slideDown();
if(data=='Message sent!') $('#contactform').slideUp();
}
);
return false;
});
});
// ]]>
</script>
</head>
<body>
<div class="main">
<div class="blok_header">
<div class="header">
<div class="search">
</div>
<div class="clr"></div>
<div class="withe_bg">
<div class="logo"></div>
<div class="menu"> </div>
<div class="clr"></div>
<div class="body">
<h3> </h3>
<p> </p>
<div class="left">
<h2>Send us a Message:</h2>
<p>Please use this convenient form to your send your message, and we will get back to you shortly.</p>
<form action="contact.php" method="post" id="contactform">
<ol>
<li>
<label for="name">Name <span class="red">*</span></label>
<input id="name" name="name" class="text" />
</li>
<li>
<label for="telephone">Telephone <span class="red"></span></label>
<input id="telephone" name="telephone" class="text" />
</li>
<li>
<label for="email">Your email <span class="red">*</span></label>
<input id="email" name="email" class="text" />
</li>
<li>
<label for="company">Company</label>
<input id="company" name="company" class="text" />
</li>
<li>
<label for="subject">Subject</label>
<input id="subject" name="subject" class="text" />
</li>
<li>
<label for="message">Message <span class="red">*</span></label>
<textarea id="message" name="message" rows="6" cols="50"></textarea>
</li>
<li class="buttons">
<input type="image" name="imageField" id="imageField" src="images/send.gif" class="send" />
<div class="clr"></div>
</li>
</ol>
</form>
</div>
<div class="right last">
<p> </p>
<p>
</p>
</div>
<div class="clr"></div>
</div>
<div class="clr"></div>
</div>
<div class="clr"></div>
</div>
</div>
<div class="clr"></div>
</div>
<div class="FBG">
<div class="FBG_resize">
<div class="clr"></div>
</div>
<div class="clr"></div>
</div>
</div>
<div class="clr"></div>
</div>
<div class="FBG">
<div class="FBG_resize">
<div class="clr"></div>
</div>
<div class="clr"></div>
</div>
<div class="footer">
<div class="footer_resize">
<p class="leftt"> </p>
<div class="clr"></div>
</div>
<div class="clr"></div>
</div>
</body>
</html>
And still does not work.....
this isn't the form itself, it's the form processor. you probably have an HTML file somewhere with the form, posting to this contact.php file.
anyway, it looks like you have to match the # of fields you're requesting in the form to the # of items (with the correct names) in the $values array. It also looks like you can require certain ones in the $required array.
change the $your_email to your email address.
you should get the emails through the form.
does that answer your question? It wasn't terribly specific.
The fix is:
edit the: $required = array('name','email','telephone','message');
And it works... 100% - thanks all...
If you want it to email to multiple people, you should take a look at the parameters section (the To section)here. This will go in your
$your_email = "myemail#live.ca";
Here's an example:
$your_email = "<user#example.com>, Another User <anotheruser#example.com>";
That should send it to user#example.com and anotheruser#example.com
You mean you want the contact mail to be sent to you also,right? if so try the following code. mail is the php mail function which done the trick. For more reference you can check the MANUAL.
<?php
$email = $_POST['email'];
//$error[] = preg_match('/\b[A-Z0-9._%-]+#[A-Z0-9.-]+\.[A-Z]{2,4}\b/i', $_POST['email']) ? '' : 'INVALID EMAIL ADDRESS';
if(!eregi("^[a-z0-9]+([_\\.-][a-z0-9]+)*" ."#"."([a-z0-9]+([\.-][a-z0-9]+)*)+"."\\.[a-z]{2,}"."$",$email )){
$error.="Invalid email address entered";
$errors=1;
}
if($errors==1) echo $error;
else{
$values = array ('name','email','message');
$required = array('name','email','message');
$your_email = "seanbridge#live.ca";
$email_subject = "New Message: ".$_POST['subject'];
$email_content = "new message:\n";
foreach($values as $key => $value){
if(in_array($value,$required)){
if ($key != 'subject' && $key != 'company') { if( empty($_POST[$value]) ) { echo 'PLEASE FILL IN REQUIRED FIELDS'; exit; }
}
$email_content .= $value.': '.$_POST[$value]."\n";
}
}
if(#mail($your_email,$email_subject,$email_content)) {
echo 'Message sent!';
} else {
echo 'ERROR!';
}
$myEmail = "myemai#your.com";//put your email address here
if(#mail($myEmail,$email_subject,$email_content)) {
echo 'Message sent!';
} else {
echo 'ERROR!';
}
}
?>

Categories