Welcome!

And don't forget to edit your signature & profile.

 

Icon

Statistics

  • Total posts 23318
  • Total topics 4048
  • Total members 5574
  • Our newest member
    ALF5583

TOP POSTERS

[Tutorial] Manage PHP forms like a pro

All problems and developments related to PHP, Ruby on Rails & Co. are discussed and resolved here.
   

[Tutorial] Manage PHP forms like a pro

Postby ibernat » Tue Oct 20, 2009 5:20 am

I see a lot of requests on the forum regarding the simplest things in PHP like sending form entries via email. So I think it'd be good to write a tutorial covering just that, PHP forms.

So how does a form look like? It's just plain HTML probably called index.html
Code: Select all
<form method="get" action="search.php">
<input type="text" name="question" />
<input type="submit" name="submit" value="Search" />
</form>


Let's break this down into pieces to get a better understanding

Code: Select all
<form method="get" action="search.php">

This is the opening part of the form. Anything between this and </form> will be treated as a form element. There are two attributes. Method says HOW the form data will be sent and Action says WHERE the data will be sent. If our current page is a HTML page we need to send it to a PHP script, thus search.php

Clicking the submit button we'll get something like
Code: Select all
search.php?question=How+are+you&submit=Submit


Specifying the method attribute as GET anything we input into the form will be sent to the script for processing as a part of the URI delimited by "&".

If we were to say method was POST then the form details would be sent in a different way, without exposing the data in our URI. Thus, we'd only have the following in our URL.
Code: Select all
search.php


The <input /> element is obviously an element that can accept data (text, files). It usually has three attributes
  • type - what kind of input is this. "text" accepts text. "submit" is a button for submitting the form data. "hidden" contains text, but is invisible to the user. There are more types, these will come by later.
  • name - we obviously need to give our input a name. E.g. date_of_birth or home_town is fine
  • value - this let's us pre-enter a value for the input. We gave our submit button a "Submit" text

Next up: How to "read" the data sent in our PHP script.
Freelance PHP and CSS developer in love with jQuery and CakePHP. Playing with Django and AppEngine.

Portfolio -PSD to HTML slicing -Twitter
User avatar
ibernat
Smashing <hr />
 
Posts: 54
Joined: Mon Feb 09, 2009 4:07 pm
Location: Zagreb, Croatia / London, UK
   

   

Re: [Tutorial] Manage PHP forms like a pro

Postby ibernat » Tue Oct 20, 2009 5:44 am

Part 2

Okay, finally something fun! You probably know you need a server to do the following. If you don't have a local server on your computer you might want to install one.

Search.php

Every PHP script starts with <?php and ends with ?> Thus a simple PHP script would look like this
Code: Select all
<?php
echo "Hello, world!";
?>


This would output -> Hello, world! <- to the screen. If you need a more newbie tutorial, post a comment below and I'll write an intro to PHP tutorial ;)

We gave our for a method="get" attribute. This means we'll read the data on the server side (PHP) the same way.
Code: Select all
<?php
echo $_GET["question"];
?>


And in case we entered something in the input box we'd get the same text out. Same goes if we used "POST" as out method of sending the data.
Code: Select all
<?php
echo $_POST["question"];
?>


If we have more then one input box, let's say a first_name, a last_name and age we would have to do three $_POST calls, like this:
Code: Select all
<?php
echo "First name: " . $_POST["first_name"];
echo "Last name: " . $_POST["last_name"];
echo "Age: " . $_POST["age"];
?>


The "." (dot) between "First name" and $_POST is there to glue the two together and print them out in the same line. Notice that even if the echo statements are in separate rows the content get's printed out in a single line. You can fix this by adding a <br/> after each line.
Code: Select all
<?php
echo "First name: " . $_POST["first_name"];
echo "<br/>";
echo "Last name: " . $_POST["last_name"];
?>


This is one of the ways you can print out HTML with PHP. Again, newbies can ask for a more intro tutorial.

Next up: Checking if the data submitted is empty or not.
Freelance PHP and CSS developer in love with jQuery and CakePHP. Playing with Django and AppEngine.

Portfolio -PSD to HTML slicing -Twitter
User avatar
ibernat
Smashing <hr />
 
Posts: 54
Joined: Mon Feb 09, 2009 4:07 pm
Location: Zagreb, Croatia / London, UK
   

   

Re: [Tutorial] Manage PHP forms like a pro

Postby ibernat » Tue Oct 20, 2009 6:18 am

Part 3

In this part we'll only check if the form had been submitted and if the fields are empty or not. More advanced validation (e.g. email, numbers) will be covered in an upcoming tutorial. Same goes for check boxes, radio buttons and other elements.

To make things more fun, create a index.php file with a form accepting a first_name, last_name and age
Code: Select all
<form method="post" action="index.php">
<input type="text" name="first_name" />
<input type="text" name="last_name" />
<input type="text" name="age" />
<input type="submit" name="submit" value="Send" />
</form>


Also, you should write all your PHP code before ANY HTML code. So any PHP goes straight to the top of your file, even before the <html> tag.

So, how do you check if a form has been submitted? This piece of PHP does the trick
Code: Select all
<?php
if(!empty($_POST)) {
   print_r($_POST);
}
?>


The PHP manual says the empty function checks if a variable is empty or not. Fair enough. If we've only loaded the page for the first time, the $_POST variable shouldn't even exist as we haven't sent any data. But once you click the submit button the $_POST fills up with the values from the form. Even if the fields are empty you still get the input keys (first_name, last_name, age).

The simplest way to validate a form is to write a generic validation class. Remember, this is only a simple class to check if a field is empty or not. More advanced stuff is yet to come.
Code: Select all
class ValidateFields {
   var $fields = array();
   
   function addField($name) {
      $this->fields[] = $name;
   }
}


What this does is it contains a list of fields we want to check if they are empty or not. To use it, you would do something like this:
Code: Select all
<?php
$vf = new ValidateForm;
$vf->addField("first_name");
$vf->addField("last_name");
$vf->addField("age");
?>


This is a bit more advanced PHP, so if you're having a hard time understanding this, post a reply below.

Now you're thinking: "Fine, I have a list of fields, but how does this check if they are empty or not?". We need to add a validate() method to our class!

Code: Select all
function validate($what) {
   $total = 0;
   
   foreach($this->fields as $field) {
      if($what[$field] == "") { $total++; }
   }
   
   if($total == 0) { return true; } else { return false; }
}


What this does is it takes an array as an argument and checks it's fields against the list of predefined fields. If the fields (any field) in the argument array are empty it will return false. This way we can use the class for both $_POST and $_GET.

Sample usage:
Code: Select all
<?php
if(!empty($_POST)) {
   if($vf->validate($_POST)) {
      print_r($_POST);
   } else {
      echo "All fields are required";
   }   
}
?>


If the form is OK, we'll get a nice dump of all the input fields provided by the print_r function. If any of the fields is empty, a "All fields are required" message will appear.

Next up: Styling and emailing the input results. 8-)
Freelance PHP and CSS developer in love with jQuery and CakePHP. Playing with Django and AppEngine.

Portfolio -PSD to HTML slicing -Twitter
User avatar
ibernat
Smashing <hr />
 
Posts: 54
Joined: Mon Feb 09, 2009 4:07 pm
Location: Zagreb, Croatia / London, UK
   

   

Re: [Tutorial] Manage PHP forms like a pro

Postby ibernat » Tue Oct 20, 2009 6:41 am

Part 4

So, we have our data and we made sure it's not empty. But doing a print_r is so ugly. Is there anything we can do about it? Yes, there is! Write our own function to style the output!

Code: Select all
<?php
function dataStyler($data, $replacement_keys=null) {
   
   $result = "<table>";
   
   foreach($data as $key=>$value) {
   $result .= "<tr>";
   
   if(is_array($replacement_keys)) {
      $key = $replacement_keys[$key];
   }
   $result .= "<td>" . $key . "</td>";
   $result .= "<td>" . $value . "</td>";
   
   $result .= "</tr>";
   }
   
   $result .= "<table>";
   
   return $result;
   
}
?>

What this does is it takes an input array ($_POST, $_GET) and a set of replacement keys and it outputs a nice HTML table that you can either print out on the screen, email to someone or store in a file.

Let's see how it works and what exactly are the replacement keys:
Code: Select all
<?php
if(!empty($_POST)) {
   if($vf->validate($_POST)) {
      unset($_POST['submit']);
      echo dataStyler($_POST, array('first_name'=>'First name:', 'last_name'=>'Last name:', 'age'=>'Age'));
   } else {
      echo "All fields are required";
   }   
}
?>


This is the same piece of code we used earlier, we still have the validation in place, but now we unset the $_POST["submit"]. Why? Well, we don't really need the submit button in out results, right? And then we do an echo dataStyler($_POST, ...); dataStyler only returns the results, it doesn't echo them out, thus the echo in front.

But what is this?
Code: Select all
, array('first_name'=>'First name:', 'last_name'=>'Last name:', 'age'=>'Age')


I figured it'd be ugly to have a table saying "first_name Ivan". So you provide as set of replacement keys for the original form input fields. (you don't have to BTW, the function works well even if the second parameter is missing).

The only thing we have left is to e-mail these results to ourselves or a client, a friend, our mums..

The official PHP manual says that the mail function looks like this
Code: Select all
bool mail  ( string $to  , string $subject  , string $message  [, string $additional_headers  [, string $additional_parameters  ]] )


So after we have validated our form, we use this mail function like this:
Code: Select all
<?php
if(!empty($_POST)) {
   if($vf->validate($_POST)) {
      unset($_POST['submit']);
      $result = dataStyler($_POST, array('first_name'=>'First name:', 'last_name'=>'Last name:', 'age'=>'Age'));
      
      mail('myemail@somemail.com', 'Some nice email title', $result);
      echo 'Results sent via email';
   } else {
      echo "All fields are required";
   }   
}
?>


Notice we return the dataStyler results in a $result variable and we send that as our email body.

Next up: More field types, better validation, better results styling :D
Freelance PHP and CSS developer in love with jQuery and CakePHP. Playing with Django and AppEngine.

Portfolio -PSD to HTML slicing -Twitter
User avatar
ibernat
Smashing <hr />
 
Posts: 54
Joined: Mon Feb 09, 2009 4:07 pm
Location: Zagreb, Croatia / London, UK
   

   

Re: [Tutorial] Manage PHP forms like a pro

Postby JonathanB » Thu Oct 22, 2009 11:34 pm

Nice tutorial! Keep it up. :)
PHP Programming Tutorials
Easily learn programming in PHP with step by step tutorials!
User avatar
JonathanB
Smashing <table>
 
Posts: 29
Joined: Tue May 19, 2009 6:27 pm
   


Return to Server-side Scripting



Who is online

Users browsing this forum: No registered users and 1 guest

cron