Contact Form

  • (2 Pages)
  • +
  • 1
  • 2

20 Replies - 4377 Views - Last Post: 02 June 2011 - 05:50 AM Rate Topic: -----

#1 nick2price  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 562
  • View blog
  • Posts: 2,826
  • Joined: 23-November 07

Contact Form

Posted 01 June 2011 - 12:04 PM

Hey, so I have some xhtml with a basic form. Nothing special going on there. When I click submit, it processes some php which I will show below. What I am trying to work out is how to get the errors to show back on my form, rather than in a new page where the user needs to click back button to get back to the form.
Any advise appreciated
cheers
<?php
if(isset($_POST['submit'])) {
     
    $email_to = "test@hotmail.co.uk";
    $email_subject = "Kontakt";
     
    function died($error) {
        echo "We are very sorry, but there were error(s) found with the form you submitted. ";
        echo "These errors appear below.<br /><br />";
        echo $error."<br /><br />";
        echo "Please go back and fix these errors.<br /><br />";
        die();
    }
     
    // validation expected data exists
    if(!isset($_POST['name']) ||
        !isset($_POST['email']) ||
        !isset($_POST['message'])) {
        died('We are sorry, but there appears to be a problem with the form you submitted.');      
    }
     
    $name = $_POST['name']; // required
    $email = $_POST['email']; // required
    $message = $_POST['message']; // required
     
    $error_message = "";
    
    $string_exp = "/^[A-Za-z .'-]+$/";
  if(!preg_match($string_exp,$name)) {
    $error_message .= 'The Name you entered does not appear to be valid.<br />';
  }
  $email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
  if(!preg_match($email_exp,$email)) {
    $error_message .= 'The Email Address you entered does not appear to be valid.<br />';
  }
  if(strlen($message) < 2) {
    $error_message .= 'The Message you entered do not appear to be valid.<br />';
  }
  if(strlen($error_message) > 0) {
    died($error_message);
  }
    $email_message = "Form details below.\n\n";
     
    function clean_string($string) {
      $bad = array("content-type","bcc:","to:","cc:","href");
      return str_replace($bad,"",$string);
    }
     
    $email_message .= "Name: ".clean_string($name)."\n";
    $email_message .= "Email: ".clean_string($email)."\n";
    $email_message .= "Message: ".clean_string($message)."\n";
     
// create email headers
$headers = 'From: '.$email_from."\r\n".
'Reply-To: '.$email_from."\r\n" .
'X-Mailer: PHP/' . phpversion();
@mail($email_to, $email_subject, $email_message, $headers); 
?>
 
<!-- Success HTML -->
 
Thank you for contacting us. We will be in touch with you very soon.
 
<?php
}
?>


Is This A Good Question/Topic? 0
  • +

Replies To: Contact Form

#2 satis  Icon User is offline

  • D.I.C Head

Reputation: 82
  • View blog
  • Posts: 231
  • Joined: 26-May 11

Re: Contact Form

Posted 01 June 2011 - 12:28 PM

The best way to do that, in my experience, is to have the form and the form processing on the same page. I'll pseudo-code an example

<?
if($_POST['submitted']){
	//set some vars
	$valid = true;
	$error = array();

	//get data
	$value1 = $_POST['val1'];
	$value2 = $_POST['val2'];
	//etc etc
	
	//validate data
	if($value1 < 1 || $value1 > 30){
		$valid = false;
		$error['value1'] = 'You value needs to be between 1 and 30';
	}
	if($value2 != 'Hopscotch'){
		$valid = false;
		$error['value2'] = 'You must like hopscotch';
	}
	if($valid){
		//insert into database
		
		echo 'Thanks for giving me your data to sell.';
		die();
	}
}
?>
<form method='POST' action=''>
<table>
<tr><td>Value1:</td><td><input name='val1' value='<?=$value1 ?>'></td><td><?=$error['value1'] ?></td></tr>
<tr><td>Favorite Sport:</td><td><input name='val2' value='<?=$value2 ?>'></td><td><?=$error['value2'] ?></td></tr> 
</table>
<input type='submit' name='submitted' value='true'>
</form>




This is obviously just made up, but I think it demonstrates what I mean.

This post has been edited by satis: 01 June 2011 - 12:29 PM

Was This Post Helpful? 0
  • +
  • -

#3 nick2price  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 562
  • View blog
  • Posts: 2,826
  • Joined: 23-November 07

Re: Contact Form

Posted 01 June 2011 - 12:41 PM

I was thinking about that, but being a java programmer, I prefere keeping my php seperate to the xhtml.
Was This Post Helpful? 1
  • +
  • -

#4 codeprada  Icon User is offline

  • Changed Man With Different Priorities
  • member icon

Reputation: 947
  • View blog
  • Posts: 2,355
  • Joined: 15-February 11

Re: Contact Form

Posted 01 June 2011 - 12:48 PM

You should. Another way of doing it is by setting a session variable.

<?php
session_start();
$_SESSION['error'] = "Incorrect username or password";
?>



<html>
<body>
<div id="error_display">
<?php 
session_start();
if(isset($_SESSION['error']))
{
	echo $_SESSION['error'];
	unset($_SESSION['error']);
}
?>
</div>
<form>
...
</form>
</body>
</html>



You can also use GET variables to get the information across but that makes nasty URLs. Another way is via cookies.

This post has been edited by codeprada: 01 June 2011 - 12:49 PM

Was This Post Helpful? 1
  • +
  • -

#5 satis  Icon User is offline

  • D.I.C Head

Reputation: 82
  • View blog
  • Posts: 231
  • Joined: 26-May 11

Re: Contact Form

Posted 01 June 2011 - 12:50 PM

That makes it more difficult, but it's still doable. In case of an error, you could just include() your original html form. Though you'd still need to have inline PHP in order to echo out the errors.

This post has been edited by satis: 01 June 2011 - 12:50 PM

Was This Post Helpful? 1
  • +
  • -

#6 nick2price  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 562
  • View blog
  • Posts: 2,826
  • Joined: 23-November 07

Re: Contact Form

Posted 01 June 2011 - 12:55 PM

I think I will go the sessions way, as I used this with a login form before.

cheers guys
Was This Post Helpful? 0
  • +
  • -

#7 nick2price  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 562
  • View blog
  • Posts: 2,826
  • Joined: 23-November 07

Re: Contact Form

Posted 01 June 2011 - 01:30 PM

Hey, so I become slightly stuck. On my xhtml page, at the very top I start a session, as if I remember correctly this should be done first. Further down the page, I have it like so
<div id="errors">
    <?php 
	if(isset($_SESSION['errorName']))
	{
		echo $_SESSION['errorName'];
		unset($_SESSION['errorName']);
	}
	if(isset($_SESSION['errorEmail']))
	{
		echo $_SESSION['errorEmail'];
		unset($_SESSION['errorEmail']);
	}
	if(isset($_SESSION['errorMessage']))
	{
		echo $_SESSION['errorMessage'];
		unset($_SESSION['errorMessage']);
	}
  ?>
  </div>
  <form id="test" method="POST" action="mailer.php">

Where my errors are printed, and the start of the form etc. As for mailer.php, I have changed it to be like
<?php
session_start();
if(isset($_POST['submit'])) {
     
    $email_to = "test@hotmail.co.uk";
    $email_subject = "Kontakt";
    
    $name = $_POST['name']; // required
    $email = $_POST['email']; // required
    $message = $_POST['message']; // required
     
    $error_message = "";
    
    $string_exp = "/^[A-Za-z .'-]+$/";
  if(!preg_match($string_exp,$name)) {
    $_SESSION['errorName'] = "The Name you entered does not appear to be valid.<br />";
  }
  $email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
  if(!preg_match($email_exp,$email)) {
    $_SESSION['errorEmail'] = "The Email Address you entered does not appear to be valid.<br />";
  }
  if(strlen($message) < 2) {
    $_SESSION['errorMessage'] = "The Message you entered do not appear to be valid.<br />";
  }
    $email_message = "Form details below.\n\n";
     
    function clean_string($string) {
      $bad = array("content-type","bcc:","to:","cc:","href");
      return str_replace($bad,"",$string);
    }
     
    $email_message .= "Name: ".clean_string($name)."\n";
    $email_message .= "Email: ".clean_string($email)."\n";
    $email_message .= "Message: ".clean_string($message)."\n";
     
// create email headers
$headers = 'From: '.$email_from."\r\n".
'Reply-To: '.$email_from."\r\n" .
'X-Mailer: PHP/' . phpversion();
@mail($email_to, $email_subject, $email_message, $headers); 
?>
 
<!-- Success HTML -->
 
Thank you for contacting us. We will be in touch with you very soon.
 
<?php
}
?>


At the moment, everything displays fine (I was getting the header issue, but resolved this). However, If I enter nothing into any of the fields and click on submit, it takes me to a page and displays
Thank you for contacting us. We will be in touch with you very soon.
Where it should be staying on the form and displaying the error messages. Am I missing something here?

cheers
Was This Post Helpful? 0
  • +
  • -

#8 RPGonzo  Icon User is offline

  • // Note to self: hmphh .... I forgot
  • member icon

Reputation: 151
  • View blog
  • Posts: 954
  • Joined: 16-March 09

Re: Contact Form

Posted 01 June 2011 - 02:02 PM

In your mailing page you never check to see if any of your errors are set ... than redirect the user back to the previous page to display those errors.

instead of having to check each error var your setting it may be easier to just create a error array in your session variable

  if(!preg_match($string_exp,$name)) {
    $_SESSION['error'][] = "The Name you entered does not appear to be valid.<br />";
  }
  $email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
  if(!preg_match($email_exp,$email)) {
    $_SESSION['error'][] = "The Email Address you entered does not appear to be valid.<br />";
  }
  if(strlen($message) < 2) {
    $_SESSION['error'][] = "The Message you entered do not appear to be valid.<br />";
  }
  
  if (isset($_SESSION['error']) && count($_SESSION['error']) >= 1) {
	// redirect to the previous page
	header('Location: contact.php'); // this needs to change to your contact form page
	die;
  }



and your display of errors would change to something like

<div id="errors">
    <?php 
	if (isset($_SESSION['error']) && is_array($_SESSION['error'])) {
		foreach ($_SESSION['error'] as $key => $error) {
			echo $error . "<br/>";
			unset($_SESSION['error'][$key]);
		}
	}
  ?>
  </div>
  <form id="test" method="POST" action="mailer.php">


Was This Post Helpful? 1
  • +
  • -

#9 CTphpnwb  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2993
  • View blog
  • Posts: 10,343
  • Joined: 08-August 08

Re: Contact Form

Posted 01 June 2011 - 02:07 PM

Quote

<?php
if(isset($_POST['submit'])) {
     
    $email_to = "test@hotmail.co.uk";
    $email_subject = "Kontakt";
     
    function died($error) {
        echo "We are very sorry, but there were error(s) found with the form you submitted. ";
        echo "These errors appear below.<br /><br />";
        echo $error."<br /><br />";
        echo "Please go back and fix these errors.<br /><br />";
        die();
    }
 

Why would you declare a function inside an if statement?

I would not only keep the HTML separate from the PHP, I'd have in its own file. My feeling is that there is a good reason that we have different kinds of files for each language: putting them together makes each harder to read.
Was This Post Helpful? 1
  • +
  • -

#10 nick2price  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 562
  • View blog
  • Posts: 2,826
  • Joined: 23-November 07

Re: Contact Form

Posted 01 June 2011 - 02:17 PM

Ok. I have decided to go a completely new route, and follow something I did for my coursework. So in my first class, I have my divs and everything, and then inside one of these i do
<?php //Start php code
    $contactUs = new Contact(); //Instantiate the class
    $contactUs->processForm(); //Use class instance to call up function and display outcome into centerBar div
/*End php code*/ ?> 


I then have another class which is php, and it has a load of functions in it. One of them displays the form
/*showForm function echos out the form for display within HTML*/
function showForm(){
	echo "<h1>Email Form</h1>"; //Form title
	echo '<form action="'.$_SERVER['PHP_SELF'].'" method="post">'; //Form action set to call up itself
      echo '  <table>'; //form placed within table to make presentation nicer
      echo '   <tr><td>name:</td>'
          .'   <td><input type="text" name="name" size="30" maxlength="30" value="'.$this->name.'"/></td></tr>';
	  echo '   <tr><td>Email:</td>'
          .'   <td><input type="text" name="email" size="30" maxlength="30" value="'.$this->email.'"/></td></tr>';
      echo '   <tr><td>message:</td>'
          .'   <td><input type="text" name="message" size="30" maxlength="30" value="'.$this->message.'"/></td></tr>';
          
      echo '<tr><td><input type="submit" name="submit" value="Submit" /></td></tr>';
      echo '  </table>';
      echo '</form>';
}


Everything appears to be working great now. I just have one question. How could I go about adding CSS to the above form? Do I just add the id into an echo or something?

cheers
Was This Post Helpful? 0
  • +
  • -

#11 eZACKe  Icon User is offline

  • Garbage Collector

Reputation: 120
  • View blog
  • Posts: 1,278
  • Joined: 01-June 09

Re: Contact Form

Posted 01 June 2011 - 02:22 PM

View Postnick2price, on 01 June 2011 - 07:17 PM, said:

Everything appears to be working great now. I just have one question. How could I go about adding CSS to the above form? Do I just add the id into an echo or something?


Well this definitely is not keeping code separated, but yes you can just do an echo statement with a css id in it:

Something like this:
echo "<span class='whatever'>....


This post has been edited by eZACKe: 01 June 2011 - 02:22 PM

Was This Post Helpful? 1
  • +
  • -

#12 nick2price  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 562
  • View blog
  • Posts: 2,826
  • Joined: 23-November 07

Re: Contact Form

Posted 01 June 2011 - 02:32 PM

I want to keep everything seperated, cos this is how I like to work. But how much more seperated can I get? In my xhtml page, which is now a php page as I need to call php, I make a call to my class and thats all. In my class, all I have is pure php code. This is why I am echoing out the form.

p.s. on a side note, wouldnt it be more secure echoing out the form anyway, as then if someone wants to hack it they would have to do it through the server?

This post has been edited by nick2price: 01 June 2011 - 02:34 PM

Was This Post Helpful? 0
  • +
  • -

#13 RPGonzo  Icon User is offline

  • // Note to self: hmphh .... I forgot
  • member icon

Reputation: 151
  • View blog
  • Posts: 954
  • Joined: 16-March 09

Re: Contact Form

Posted 01 June 2011 - 02:45 PM

your actually not separating at all your still combining and going in and out of PHP & HTML

A true separation would be to create or use a template engine. which would give you one file with nothing but HTML no echos from PHP necessary with placeholders for your data.

the other file would be a processing script entirely composed of PHP not skipping in and out of HTML.

http://www.dreaminco...ode-separation/
Was This Post Helpful? 2
  • +
  • -

#14 Jstall  Icon User is offline

  • Lurker
  • member icon

Reputation: 434
  • View blog
  • Posts: 1,042
  • Joined: 08-March 09

Re: Contact Form

Posted 01 June 2011 - 02:53 PM

It is fairly easy to write a simple templating class to handle the functionality shown in the tutorial RPGonzo linked. Or you could use a 3rd party library. I use Smarty where I work and it's pretty easy to pick up.
Was This Post Helpful? 0
  • +
  • -

#15 RPGonzo  Icon User is offline

  • // Note to self: hmphh .... I forgot
  • member icon

Reputation: 151
  • View blog
  • Posts: 954
  • Joined: 16-March 09

Re: Contact Form

Posted 01 June 2011 - 02:56 PM

Smarty is extremely easy to setup and use and quite flexible ;-)
Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2