Jump to content

php contact form errors...


robolist

Recommended Posts

I am fairly new to php and am just about to finish my website with its contact page. It is all working fine and i am receiving the email with the relevant information submitted. But there are few tweeks i would like to make, so it appears more professional.

 

1. For the validation I have selected it to validate three fields, email, name and message. I have tested it but the error messages are not separated. I mean if only one mistake is made then the error message appears under all three fields.

 

2. When I receive the email from whoever filled in the form I would like for their email address to be in the 'reply' and 'from' field in my email.

 

I would be very grateful if anybody can help me out on these two problems I am having.

 

Below is the code that i am currently using.

 

(Where the errors occur i place the following code

<?php echo $myError; ?>

)

 

The following is my entire php code, which my html form directs to...

 

<?php
/* Set e-mail recipient */
$myemail  = "myemailaddress@gmail.com";

/* Check all form inputs using check_input function */
$name = check_input($_POST['name'], "Please enter your name");
$subject = "Message from Keeper Website";
$email    = check_input($_POST['email'], "Please enter your email address");
$how_find = check_input($_POST['how']);
$comments = check_input($_POST['comments'], "Please write your message");

/* If e-mail is not valid show error message */
if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/", $email))
{
    show_error("E-mail address not valid");
}


/* Let's prepare the message for the e-mail */
$message = "Hello,

Your contact form has been submitted by:

Name: $name
E-mail: $email
How did he/she find out about us? $how_find

Comments:
$comments

End of message
";

/* Send the message using mail() function */
mail($myemail, $subject, $message);

/* Redirect visitor to the thank you page */
header('Location: thanks.html');
exit();

/* Functions we used */
function check_input($data, $problem='')
{
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    if ($problem && strlen($data) == 0)
    {
        show_error($problem);
    }
    return $data;
}

function show_error($myError)
{
?>

 

Many thanks in advance

Link to comment
Share on other sites

It probably appears under all three fields because you're using the same variable for all three errors. No way to tell though since you didn't post that part.

HINT: I'd use an array of errors with field names as keys.

 

Thanks for your help... I am very new to php and not really sure exactly how to fix this... I understand what you mean about using an array to determine the separate errors. But i just dont know how to implement it. Below is the entire code for my page... I would be ever so grateful if you could help me out...

<?php
/* Set e-mail recipient */
$myemail  = "@gmail.com";

/* Check all form inputs using check_input function */
$name = check_input($_POST['name'], "Please enter your name");
$subject = "Message from Keeper Website";
$email    = check_input($_POST['email'], "Please enter your email address");
$how_find = check_input($_POST['how']);
$comments = check_input($_POST['comments'], "Please write your message");

/* If e-mail is not valid show error message */
if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/", $email))
{
    show_error("E-mail address not valid");
}



/* Let's prepare the message for the e-mail */
$message = "Hello,

Your contact form has been submitted by:

Name: $name
E-mail: $email
How did he/she find out about? $how_find

Comments:
$comments

End of message
";

/* Send the message using mail() function */
mail($myemail, $subject, $message);

/* Redirect visitor to the thank you page */
header('Location: thanks.html');
exit();

/* Functions we used */
function check_input($data, $problem='')
{
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    if ($problem && strlen($data) == 0)
    {
        show_error($problem);
    }
    return $data;
}

function show_error($myError)
{
?>

    







<html>
<head>
<title>Contact </title>
<meta name="google-site-verification" content="0idS3GHHR3bAfMMatJ2XYirKyVSNBZzCfyFja-3690Y" />
<meta http-equiv="X-UA-Compatible" content="IE=8" />
<meta http-equiv="Content-type" content="text/html; charset=UTF-8" />
<meta name="description" content=." />
<meta name="keywords" content="" />
<meta name="author" content="com" />
<link rel="stylesheet" type="text/css" href="css/master.css">
<link rel="stylesheet" type="text/css" href="css/form.css">
<link rel="shortcut icon" href="favicon.ico" >
<link rel="icon" type="image/gif" href="favicon1.gif" >
<script type="text/javascript">
function setfocus() {
document.contactform.name.focus();
}
</script>

</head>

<body onLoad="setfocus()">
<div id="page-container">


		<div id="navigation"> 
<ul> 
	<li><a href="index.html"><span><b>Home</b></span></a></li> 
	<li><a href="class.html"><span><b>Cooking Class</b></span></a></li> 
	<li><a href="menu.html"><span><b>Our Menu</b></span></a></li> 
	<li><a href="herbs.html"><span><b>Herbs</b></span></a></li>		
	<li class="last"><a href="contact.html"><span><b>Contact Us</b></span></a></li> 
</ul> 
		</div> 
<div id="content-menu">






				<div id="contact">
						<center>
						<h1>Contact </h1>
						<p>If you would like to recieve more information on our cooking class, menu or just need directions. <br>
						Please feel free to contact us using the form below.<br/>
						<b>For a map to find Restaurant, <a href="images/_map.png" onclick="centeredPopup(this.href,'myWindow','371','233','yes');return false">please click here</a></p></b>


						<form id="form3" action="contact.php" method="post" name="contactform">	
							<h3><span>Contact Us</span></h3>
								<fieldset><legend>Contact form</legend>
									<p class="first">
										<label for="name">Name <b><?php echo $myError; ?></b></label>
										<input type="text" name="name" id="name" size="30" />
									</p>

									<p>
										<label for="email">Email <b><?php echo $myError; ?></b></label>
										<input type="text" name="email" id="email" size="30" />
									</p>

									<p>
										<label for="how">How did you find us?</label>
											<select name="how" width="50">
												<option value=""> -- Please select -- </option>
												<option>Google</option>
												<option>Yahoo</option>
												<option>Link from a website</option>
												<option>Word of mouth</option>
												<option>Other</option>
											</select>
									</p>
								</fieldset>

								<fieldset class="last">																					
									<p>
										<label for="comments">Message</label>
										<b><?php echo $myError; ?></b>
										<textarea name="comments" id="comments" cols="30" rows="10"></textarea>
									</p>					
								</fieldset>					
									<p class="submit">
										<button type="submit">Send</button>
									</p>			
						</form>		
						<p>


				</div>		

</div>


</div>
<p align="center">Copyright &copy ------</p>


<script language="javascript">
var popupWindow = null;
function centeredPopup(url,winName,w,h,scroll){
LeftPosition = (screen.width) ? (screen.width-w)/2 : 0;
TopPosition = (screen.height) ? (screen.height-h)/2 : 0;
settings =
'height='+h+',width='+w+',top='+TopPosition+',left='+LeftPosition+',scrollbars='+scroll+',resizable'
popupWindow = window.open(url,winName,settings)
}
</script>





</body>
</html>	




<?php
exit();
}
?>

 

Link to comment
Share on other sites

Start trying, and then ask for help when it doesn't work.

 

OK... I hate to say but I have failed in my efforts... I tried to make an array out of the $data, and the $myError.

 

Finally I separated the three errors by $myError = array('error1', 'error2', 'error3') --(example only)--- And then with the echo using 0,1 & 2. It kind of worked but instead all separate errors came up all together LOL... even when one was not an error...  OMG I am going crazy trying to figure this out... I know once i see it i will kick myself...

 

but please can you help me out??

 

many many thanks in advance...

Link to comment
Share on other sites

Initialize an empty $errors array, then each time a field validation fails, just add to the $errors array. If the $errors array is empty, proceed to process the data, else, display the errors along with the form to allow the user to make corrections and resubmit. This is just a stock example I use to illustrate the theory behind it, it should give you enough info to get something working. Paste it in and try it and see how it handles the different errors.

 

<?php
if( $_POST['submitted'] == 'yes' ) { //check for hidden field value to indicate form has been submitted
   $errors = array(); // initialize an array to hold validation errors
   array_map('trim', $_POST); // trim all $_POST array values

   if( !empty($_POST['name']) ) { // validate the name field
      if( !ctype_alpha($_POST['name']) ) {
         $errors[] = 'Name must be alphabetic characters only.'; // if name has non alpha chars, store error
      }
      if( strlen($_POST['name']) < 3 || strlen($_POST['name'] > 20) ) {
         $errors[] = 'Name must be from 3 to 20 characters.'; // if name has too many/few chars, store error
      }
   } else {
      $errors[] = 'Name is a required field.'; // if name is empty, store error
   }

   if( !empty($_POST['number']) ) { // same validations as in name, above.
      if( !ctype_digit($_POST['number']) ) {
         $errors[] = 'Number must be numeric.';
      }
      if( strlen($_POST['number']) < 5 || strlen($_POST['number']) > 20 )  {
         $errors[] = 'Number must be from 5 to 20 digits. It is currently ' . strlen($_POST['number']) . ' digits';
      }
   } else {
      $errors[] = 'Number is a required field.';
   }

   if( !empty($errors) ) {  // if the $errors array is not empty, display the errors to allow the user to correct them and resubmit the form
      echo "<font color=\"red\">The following errors were detected";
      foreach( $errors as $value ) {
         echo "<br>$value";
      }
      echo '</font>';
   }
}
?>

<form method="post">
Name (3-20 letters): <input type="text" name="name" value="<?php echo isset($_POST['name']) ? $_POST['name'] : ''; ?>"><br>
Number (5-10 numbers): <input type="text" name="number" value="<?php echo isset($_POST['number']) ? $_POST['number'] : ''; ?>"><br>
<input type="hidden" name="submitted" value="yes">
<input type="submit" name="submit" value="Submit">
</form>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.