Basic server-side validation

Where are we?

We just looked at client-side validation with JavaScript. Time to start working on the server side.

This lesson’s goals

By the end of this lesson, you should:

  • Understand why you need server-side and client-side validation.
  • Know how to check whether a value sent to the server is a valid number.

The need for server-side validation

You need to validate form data on the server (with PHP) as well as on the client (with JavaScript). Why? Three reasons.

Reason 1: There are some checks you can only do on the server.

Suppose you have an online store selling dog toys. A user enters the number of toys s/he wants:

Ordering toy

Figure 1. Ordering toy

Maybe you’ve sold out of the Giant Chew Rope. You want to tell the user:

Out of stock

Figure 2. Out of stock

The code for this will be something like:

if number_ordered > current_inventory then

(This is pseudocode, of course.)

You get number_ordered from the form the user filled out. But where does current_inventory come from?

As you’ll learn later, you look that up in a database. This is typical:

DB lookup

Figure 3. DB lookup

The if statement above is usually done by PHP code on the server, not the browser. The server has access to the database. The browser does not.

Reason 2: Security.

This is the second reason why you do validation on the server as well as the browser.

Remember that every page a user sees in his or her browser is downloaded to his or her computer. That includes the JavaScript that has the validation code.

A clever hacker might be able to create a new version of your page, without the JavaScript checking. S/he could then fool your server into accepting invalid data.

Reason 3: Coding mistakes.

You might make a mistake coding the JavaScript. For example, you might write:

if ( age = "" ) { //WRONG!
   Tell the user the field is empty
else {
   Accept the data

The first line is wrong. It should be:

if ( age == "" ) {

An easy thing to miss, but it could mean that you get bad data in your databases. This can mess up sales, event registration, or whatever business your Web site supports.

So, even though you know how to do validation by writing JavaScript that runs on a browser, you also need to know how to do it on a server. Because:

  • There are some checks you can only do on the server.
  • Security.
  • Coding mistakes.

Simple validation

Let’s start out easy (as usual). Let’s make this:

Empty order form

Figure 4. Empty order form

The user types a number and clicks the button:

Order form with data

Figure 5. Order form with data

S/he sees this:

Order output

Figure 6. Order output

But what if the user enters an invalid number?

Bad input

Figure 7. Bad input

This is the result:

Result from bad input

Figure 8. Result from bad input

You can try it.

Here’s the page:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Strict//EN" "">
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Order Processing</title>
    <h1>Order Processing</h1>
    //Get the input.
    $giant_chew_ropes = $_POST['giant_chew_ropes'];
    //Validate input.
    if ( ! is_numeric($giant_chew_ropes) ) {
      print '<p>Invalid number.</p>';
      print '<p>Please click the Back button on your browser and try again.</p>';
    else {
      //Input OK, show the order.
      //Compute total.
      $giant_chew_ropes_total = $giant_chew_ropes * 12.95;
      //Output total.
      <p>Thank you for your order.</p>
      <table cellpadding="5" cellspacing="0" border="1">
          <th>Unit price</th>
          <th>Total price</th>
          <td>Giant chew ropes</td>
          <td><?php print $giant_chew_ropes; ?></td>
          <td>$<?php print number_format($giant_chew_ropes_total, 2); ?></td>

Figure 9. Simple validation

Line 11 gets the value the user typed into the form field:

$giant_chew_ropes = $_POST['giant_chew_ropes'];

The if statement in line 13 checks it:

if ( ! is_numeric($giant_chew_ropes) ) {
   print '<p>Invalid number.</p>';
   print '<p>Please click the Back button on your browser and try again.</p>';
else {
   Do this if number is OK.

The function is_numeric() is true if the argument it’s given is a valid number. Otherwise, it returns false. Recall that ! means “not.” So, if $giant_chew_ropes is not numeric, then output the HTML for an error message.

Remember the JavaScript isNaN() function? It returns true when a value is not a number. So isNaN() is like a backwards is_numeric(). is_numeric() is true when a value is a number, while isNaN() is true when a value is not a number.

There are some other things to notice about Figure 9. Look at the else on line 17. There’s a lot of code in the else, all the way up to line 39. That’s OK. You can put as much code as you like in braces.

Now look at line 22. This switches back from PHP to HTML mode. But it’s still inside the else! So the <table> is only shown if the user’s input passes the validation test.

The opening brace ({) in line 17 needs a closing brace (}) to go along with it. You can see that in line 39. But notice that the brace is a PHP brace. So you need to switch back to PHP mode to close the brace in line 17.

Switching modes like this is very common in PHP land. But it can be tricky for beginners. Remember that when you need to close a brace, make sure you’re in PHP mode.

Exercise: Dog weight

Create a page with a form:


Figure 1. Input

Send the form data to a PHP page. If the user enters an invalid number, show this:


Figure 2. Error

If there’s a valid number, show this:


Figure 3. Output

You can see my solution. You can also download the files. Of course, do the exercise yourself before you look at my solution.

Upload your solution to your server. Put the URL below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?


You learned:

  • Why you need server-side and client-side validation.
  • How to check whether a value sent to the server is a valid number.

What now?

Let’s see how you can do better validation.