Hi there I am currently completing a uni assignment using php and I thought it was finished until the lecturer dropped a bombshell and added another requirement. I have a contact us page which was basically just a shell (dead) page, he nows tell us that we have to do error validating on the form input with appropriate error messages, as well as echoing to the screen a message acknowledging receipt of the message when it is submitted. I am just not sure how to implement this. I am basically working with 3 files as well as the formatting files and the css, there is the contact.php, which is the basic web page, it calls in the other two files which are the includes/enquiryform.php and the includes/enquiryCheck.php. The page and the form work perfectly, but the error checking doesn't seem to do anything at all.

I will post all the code below hoping that someone can help me out of this very frustrating jam as this assignment is due on sunday and I have been working at this one final problem for 21 hours straight now and can't even think coherently any more. Oh some stuff id commented out, I have just been trying anything to try and make it work.

Also if anyone is genuinely interested in helping me out I will give you the url of where the site can be located, I am just not keen on revealing that on a public forum as it is a uni assignment and I don't want anyone copying it right now.

Cheers and sorry for rambling on I am just so very tired.

Giddyupgirl

contact.php

<?php 
//session_start();

	// relevant variables for the header
	$page_title = "School Friends Club - Contact Us";
	$page_meta_description = "School Friends Club contact us";
	$page_meta_revised = "******* - 16/08/2009";
	$page_name = "pageContact";

	require ('includes/checkEnquiry.php');

	//checkEnquiry();

	require ('includes/navigation.php');	
?>

	<!-- Content Div -->
	<div id="content">
	
	<p><img src="images/contact title.jpg" alt="Contact Us" width="720" height="60" />
    <img src="images/fancy67.gif" alt="bar" width="720" height="6" /></p>
    
	
	<!-- Contact Div - Left-side Pane -->
	<div id="contact">
	
	<h3> The School Friends Club</h3>
    
	<p>	Lourdes College, Traralgon Campus<br />
		Building 12A, Level 2, Room 7<br />
		345 - 399 Grey Street <br />
		PO Box 783 <br />
		Traralgon VIC 3844 Australia <br />
		Phone: +61 7 4651 5555<br />
		Fax: +61 7 4651 7777<br />
		Email: <a href="mailto:admin@sfc.com.au">admin@sfc.com.au</a></p>

	</div>  <!-- close contact div-->
	
	<!-- Enquiry Div - Right-side Pane -->	
 
<?php 
	require ('includes/enquiryform.php');
?>

</div> <!-- close content div-->
				
<?php 
	require ('includes/footer.php');
?>


	</div> <!-- close page div -->

	</div> <!-- close container div -->
    
</body>
</html>

includes/enquiryCheck.php

<?php 

// variable for any errors
	$errors;		
/*function checkEnquiry()*/	
{
		
	// if a user has just clicked submit, these will be set	
	if (isset($_POST["submit"])) 
	{
  		
		// create variables to hold the data$name = $_POST['name'] ;
  		$name = $_POST['name'] ;
		$email = $_POST['email'] ;
  		$question = $_POST['question'] ;

 		// if the all fields contain data
		if (!empty($name)&& !empty($email)&& !empty($question))
		{
			  
			// Make sure the name contains only letters
			
			if (ereg('[^a-zA-Z]+', $name)) 
				{
					$errors .= '<h3>Name can only contain letters.</h3>';
			    }
	
			if (ereg("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email))
				{
					$errors .= '<h3> Not a valid email address </h3>';
					
				}
			// Make sure the question contains only alphanumeric and numbers
				
			if (ereg('[^A-Za-z0-9]+', $question)) 
			{
		    	$errors .= '<p>Your question can only contain letters and numbers.</p>';
			}
		} 
		
		else 
		{
			// if the name is empty, create error
			if (empty($name)) 
			{
				$errors .= '<p>Name field cannot be empty.</p>';
			} 
			// if the email is empty, create error
			if (empty($email)) 
			{
				$errors .= '<p>Email field cannot be empty.</p>';
			}
			// if the question is empty, create error
			if (empty($question)) 
			{
				$errors .= '<p>Question field cannot be empty.</p>';
			}
			
			/*// if errors were created, print them to the screen 
			if(empty($errors))
			{
				echo '<h3>Your email was sent successfully</h3>';
			}*/
		}
	}
}
?>

includes/enquiryform.php

<div id="enquiry">
<form action="mailto:admin@******.net" method="post">
	<fieldset class="enquiryForm">
	<legend class="legendHeader">Enquiry Form</legend>
	<br />
    <label for="name">Name:</label>
    	<input type="text" id="name"></input><br />
    <label for="email">Email:</label> 
    	<input type="text" id="email" ></input><br />
    <label for="question">Question:</label>
    	<textarea rows="3" cols="20" id="question"></textarea>
    <br /><br />
		<input type="submit" value="Submit"></input>
		<input type="reset" value="Reset"></input>
    </fieldset>
	</form>
</div>  <!-- close enquiry div-->

Recommended Answers

All 13 Replies

// if errors were created, print them to the screen 
			if(empty($errors))
			{
				echo '<h3>Your email was sent successfully</h3>';
			}

Please could you provide some more details about exactly what is happening (or not happening)? i.e. is the problem just that it won't show the errors on screen, if so you just need to add to the bit I've quoted above

else
   {
	echo '<h3>Errors were detected</h3>'.$errors;
   }

If your validations aren't working, please reply with details of what is wrongly passing through the validations, so we can take a closer look at them

Hi Simon,
Thank you so much for your reply, it is basically that absolutely nothing is happening, the errors aren't caught and no error messages are displayed. It is as if the enquiryCheck isn't even there or implementing. Sorry I am probably not making much sense but I don't have the skill to use the correct terminology.

thank you
Fiona

PS I have added that snippet to the code and still nothing happens.

The bit in your code that echoes whether or not the email was sent seems to be commented out. Have you removed the comments?

/*// if errors were created, print them to the screen 
			if(empty($errors))
			{
				echo '<h3>Your email was sent successfully</h3>';
			}*/

If you remove the commenting, so your code is like below, what is echoed to the screen? If the function is being called correctly, you should get either of the two possible outputs below.

if(empty($errors))
			{
				echo '<h3>Your email was sent successfully</h3>';
			}
		else { 
				echo '<h3>Errors were detected</h3>'.$errors; 
			}

thank you Simon, yes I have done that but unfortunately it still doesn't work, I don't think the function is being called properly but I don't know how to resolve that problem.
cheers
giddyupgirl

I think I may have spotted the problem
If you are not getting either of the outputs from above, it seems the function has been commented out. Try uncommenting the following line:

//checkEnquiry();

Sorry still no luck, I have sent you a private message with the url of where the actual website is locate if that is of any use.
Thank you for your patience.
cheers
giddyupgirl

I think I've found why nothing is happening with the function.
It is probably being called on every page load, but the first thing it checks is

if (isset($_POST["submit"]))

This won't be true for 2 reasons:
1. the form contains the code:

action="mailto:admin@******.net"

So submitting the form will send all the info to the email itself, not the server. Usually on a contact form, the server will handle the emailing with php's mail() function, so it is probably best to go down that avenue. Certainly to use PHP validations, you would have to submit to the server to begin with. To do this, just remove the action="" bit of code and the form will submit to the server
2. the form elements have not been named, so on each <input> you would have to add

name='submit'

or

name='name'

as appropriate. The $_POST bit relies on a name being declared.

The next thing I would do (unless you can think of a reason why this shouldn't be the case), is run each of your validations in a series of if/elseif.
Also, please note I have spotted what I think is a final problem in your validations. They just need a ! in front to say if there is NO ereg of the following regular expression.
See below:

// if the name is empty, create error
			if (empty($name)) 
			{
				$errors .= '<p>Name field cannot be empty.</p>';
			}
			// Make sure the name contains only letters
			elseif (!ereg('[^a-zA-Z]+', $name)) 
			{
				$errors .= '<h3>Name can only contain letters.</h3>';
			}
			
			// if the email is empty, create error
			if (empty($email)) 
			{
				$errors .= '<p>Email field cannot be empty.</p>';
			}
			//if email is set, check it is valid
			elseif (!ereg("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email))
			{
				$errors .= '<h3> Not a valid email address </h3>';
			}
			
			// if the question is empty, create error
			if (empty($question)) 
			{
				$errors .= '<p>Question field cannot be empty.</p>';
			}
			// Make sure the question contains only alphanumeric and numbers
			elseif (!ereg('[^A-Za-z0-9]+', $question)) 
			{
		    	$errors .= '<p>Your question can only contain letters and numbers.</p>';
			}

The advantage of this is that it will only run the validations if the content is not empty for each element. But unlike the previous code, it will still run validations on 'name' and 'email' even if 'questions' is absent

After this, if you choose to mail from the server, you may want to look into php's mail() function. I would recommend reading up on it on the PHP manual: http://www.php.net/manual/en/function.mail.php

A very basic way of doing this would be to add code like this to send the email:

if(empty($errors))
			{
				$headers = 'Content-type: text/html; charset=iso-8859-1' . "\n";
				$headers .= 'From: '.$name."<".$email.">"."\n";
				mail(
				"example@domain.com", 
				"Mail using contact form", 
				"<html><body>".$question."</body></html>",
				$headers);
				echo '<h3>Your email was sent successfully</h3>';
			}
			else
			{
				echo '<h3>Errors were detected</h3>'.$errors;
			}

I have quickly tested some of this code, but I haven't been able to test all of it. Also when I declared the $headers variable, I copied some old code that I used over a year ago when I was new to php, so there is a bad mix of single and double quotes. You may wish to try tidying it up, but I chose not to, because I wanted to copy code that I know worked previously.
You will obviously need to go through the code and check it does what you want it to and you will need to set it to automatically email to an address of your choice and set the subject as required.

Another thing I noticed, some errors are in <h3> tags, others in <p> tags, it would be best to standardise that.

If you need anything else, please let me know.

Thank you very much Simon, I have implementent all the changes you have suggested, I am not sure if I have done them correctly as this still doesn't work for me, you can see the results on the website link I sent you, it has been a very long night. I am a little confused what do i put in the form action=?

<?php 
session_start();

	// relevant variables for the header
	$page_title = "School Friends Club - Contact Us";
	$page_meta_description = "School Friends Club contact us";
	$page_meta_revised = "xxxxxxxx - 16/08/2009";
	$page_name = "pageContact";

	require ('includes/checkEnquiry.php');
	
	checkEnquiry();

	require ('includes/navigation.php');	
?>

	<!-- Content Div -->
	<div id="content">
	
	<p><img src="images/contact title.jpg" alt="Contact Us" width="720" height="60" />
    <img src="images/fancy67.gif" alt="bar" width="720" height="6" /></p>
    
	
	<!-- Contact Div - Left-side Pane -->
	<div id="contact">
	
	<h3> The School Friends Club</h3>
    
	<p>	Lourdes College, Traralgon Campus<br />
		Building 12A, Level 2, Room 7<br />
		345 - 399 Grey Street <br />
		PO Box 783 <br />
		Traralgon VIC 3844 Australia <br />
		Phone: +61 7 4651 5555<br />
		Fax: +61 7 4651 7777<br />
		Email: <a href="mailto:admin@sfc.com.au">admin@sfc.com.au</a></p>

	</div>  <!-- close contact div-->
	
	<!-- Enquiry Div - Right-side Pane -->	
 
<?php 
	require ('includes/enquiryform.php');
?>

</div> <!-- close content div-->
				
<?php 
	require ('includes/footer.php');
?>


	</div> <!-- close page div -->

	</div> <!-- close container div -->
    
</body>
</html>
<div id="enquiry">
<form action="" method="post">
	<fieldset class="enquiryForm">
	<legend class="legendHeader">Enquiry Form</legend>
	<br />
    <label for="name">Name:</label>
    	<input type="text" id="name" name="name"></input><br />
    <label for="email">Email:</label> 
    	<input type="text" id="email" name="email"></input><br />
    <label for="message">Message:</label>
    	<textarea rows="3" cols="20" id="message" name="message"></textarea>
    <br /><br />
		<input type="submit" name="submit" value="Submit"></input>
		<input type="reset" name="submit" value="Reset"></input>
    </fieldset>
	</form>
</div>  <!-- close enquiry div-->
<?php 

// variable for any errors
	$errors;		
function checkEnquiry()	

{		
	// if a user has just clicked submit, these will be set	
	if (isset($_POST["submit"])) 
	{
  		
		// create variables to hold the data
		/*$to = "admin@xxxxxx.net";
		$subject = "SFC Enquiry";*/
  		$name = $_POST['name'] ;
		$email = $_POST['email'] ;
  		$message = $_POST['message'] ;
		
		/*$body = "From: $name_field\n E-Mail: $email_field\n Message:\n $message"; 
  
		echo "Data has been submitted to $to!"; 
		mail($to, $subject, $body);*/ 


 		// if the all fields contain data
		if (!empty($name)&& !empty($email)&& !empty($message))
		{
			  
			// if the name is empty, create error
			if (empty($name)) 
			{
				$errors .= '<h3>Name field cannot be empty.</h3>';
			}
			// Make sure the name contains only letters
			elseif (!ereg('[^a-zA-Z]+', $name)) 
			{
				$errors .= '<h3>Name can only contain letters.</h3>';
			}
			
			// if the email is empty, create error
			if (empty($email)) 
			{
				$errors .= '<h3>Email field cannot be empty.</h3>';
			}
			//if email is set, check it is valid
			elseif (!ereg("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email))
			{
				$errors .= '<h3> Not a valid email address </h3>';
			}
			
			// if the question is empty, create error
			if (empty($message)) 
			{
				$errors .= '<h3>Message field cannot be empty.</h3>';
			}
			// Make sure the message contains only alphanumeric and numbers
			elseif (!ereg('[^A-Za-z0-9]+', $message)) 
			{
		    	$errors .= '<h3>Your message can only contain letters and numbers.</h3>';
			}
			if(empty($errors))
			{
				$headers = 'Content-type: text/html; charset=iso-8859-1' . "\n";
				$headers .= 'From: '.$name."<".$email.">"."\n";
				mail(
				"admin@xxxxx.net", 
				"A Message for SFC", 
				"<html><body>".$message."</body></html>",
				$headers);
				echo '<h3>Your email was sent successfully</h3>';
			}
			else
			{
				echo '<h3>Errors were detected</h3>'.$errors;
			}
			
		}
	}
}
?>

The first problem I can see with this is that you have a line of code that says

// if the all fields contain data
		if (!empty($name)&& !empty($email)&& !empty($message))
		{

This would need to be removed, as the bit contained within that code now also validates for if the values are empty. So taking that if statement out will allow all of the validations to take place.

The action="" bit can just be removed altogether. It's not necessary when the page is submitting to itself, but I suppose it would be equally valid to say

action="contact.php"

Once you do this, you will probably find that two of your validations trigger, irrespective of what content is entered. The email validation works as expected, but I cannot seem to pass the 'name' or 'message' validations.
It's a while since I've worked with regular expressions, so I might not be able to help on that one. I'll keep looking, but you might be better off dabbling with the syntax you're using in ereg() for those two, until you get the desired effect.

Right, I think I've sorted the RegEx that you need to use.
It would be best to use eregi() instead of ereg, because it is case insensitive and will allow for people who use capital letters.

The code I have used for name validation is:

elseif (!eregi("^[a-z \-]*$", $name))

This should allow upper and lowercase text characters and also I have added a space, because a lot of people will want to enter first and last names. I have also added \- because this should allow hyphenated names. You can edit the pattern syntax to add other valid characters or remove the ones I added, depending what you need.

Similarly for the message, I have used

elseif (!eregi("^[A-Z0-9 \,\.\!\/\\]*$", $message))

I have decided here that , . ! / and \ should all be valid characters. I would suggest allowing many more characters, but this is up to you.

One other comment I have, is that when you fail a validation on any of the name, email or message; you have to retype all the details again.
To get round this, I would recommend setting variables to be picked up by the form (but only for when the message was not sent).

To do this, you would need to do something like:

else
			{
				echo '<h3>Errors were detected</h3>'.$errors;
				global $unsent_name, $unsent_email, $unsent_message;
				$unsent_name = $name;
				$unsent_email = $email;
				$unsent_message = $message;
			}

and then adjust your inputs to be like this

<input type="text" id="name" name="name" value="<? echo $unsent_name; ?>">

and textarea like this

<textarea rows="3" cols="20" id="message" name="message"><? echo $unsent_message; ?></textarea>

I hope this is helpful

Hi again Simon,
I have no idea what I am doing wrong, but it just isn't working, I type somthing into the form - a deliberate error and click on submit and it just disappears with no error message returned.

Would it be useful if I sent you all the files?

regards
Fiona

Thank you so much Simon, you are wonderful and one of the best. Problem is solved thanks to your patience and persistence.
cheers
Giddyupgirl

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.