Logo         Community
  Trog
Services
The Company
Community
Columns
Your Account
Contact Us
 
 
PHP 101 (part 13): The Trashman Cometh
Secure your PHP scripts with clever input validation tricks.

| Not My Type |

So now you know how to catch the most basic error - missing data - and stop script processing before any damage takes place. But what if the data's present, but of the wrong type or size? Your 'missing values' test won't be triggered, but your calculations and database could still be affected. Obviously, then, you need to add a further layer of security, wherein the data type of the user input is also verified.

Here's an example which illustrates:


<html>
<head></head>
<body>
<?php
if (!isset($_POST['submit'])) {
?>
    <form action = '<?php $_SERVER['PHP_SELF']?>' method = 'post'>
    How many sandwiches would you like? (min 1, max 9)
    <br />
    <input type = 'text' name = 'quantity'>
    <br />
    <input type = 'submit' name = 'submit' value = 'Save'>
    </form>
<?php
}
else {
    // check for required data
    // die if absent
    if (!isset($_POST['quantity']) || trim($_POST['quantity']) == '') {
        die ("ERROR: Can't make 'em if you don't say how many!");
    }

    // check if input is a number
    if (!is_numeric($_POST['quantity'])) {
        die ("ERROR: Whatever you just said isn't a number!");
    }

    // check if input is an integer
    if (intval($_POST['quantity']) != $_POST['quantity']) {
        die ("ERROR: Can't do halves, quarters or thirds... I'd lose my job!");
    }

    // check if input is in the range 1-9
    if (($_POST['quantity'] < 1) || ($_POST['quantity'] > 9)) {
        die ('ERROR: I can only make between 1 and 9 sandwiches per order!');
    }

    // process the data
    echo "I'm making you {$_POST['quantity']} sandwiches. Hope you can eat them all!";
}
?>
</body>
</html>


Notice that once I've established that the field contains some data, I've added a bunch of tests to make sure it meets data type and range constraints. First, I've checked if the value is numeric, with the is_numeric() function. This function tests a string to see if it is a numeric string - that is, a string consisting only of numbers.

Assuming what you've got is a number, the next step is to make sure it's an integer value between 1 and 9. To test if it's an integer, I've used the intval() function to extract the integer part of the value, and tested it against the value itself. Float values (such as 2.5) will fail this test; integer values will pass it. The final step before green-lighting the value is to see if it falls between 1 and 9. This is easy to accomplish with a couple of inequality tests.

Whilst on the topic, it's also worth mentioning the strlen() function, which returns the length of a string. This can come in handy to make sure that form input doesn't exceed a particular length. The following example shows how:


<html>
<head></head>
<body>
<?php
if (!isset($_POST['submit'])) {
?>
    <form action = '<?php $_SERVER['PHP_SELF']?>' method = 'post'>
    Enter a nickname 6-10 characters long:
    <br />
    <input type = 'text' name = 'nick'>
    <br />
    <input type = 'submit' name = 'submit' value = 'Save'>
    </form>
<?php
}
else {
    // check for required data
    // die if absent
    if (!isset($_POST['nick']) || trim($_POST['nick']) == '') {
        die ('ERROR: Come on, surely you can think of a nickname! How about Pooky?');
    }

    // check if input is of the right length
    if (!(strlen($_POST['nick']) >= 6 && strlen($_POST['nick']) <= 10)) {
        die ("ERROR: That's either too long or too short!");
    }

    // process the data
    echo "I'll accept the nickname {$_POST['nick']}, seeing as it's you!";
}
?>
</body>
</html>


Here, the strlen() function is used to verify that the string input is neither too long nor too short. It's also a handy way to make sure that input data satisfies the field length constraints of your database. For example, if you have a MySQL VARCHAR(10) field, strings over 10 characters in length will be truncated. The strlen() function can serve as an early warning system in such cases, notifying the user of the length mismatch and avoiding data corruption.


How to do Everything with PHP & MySQL
How to do Everything with PHP & MySQL, the best-selling book by Melonfire, explains how to take full advantage of PHP's built-in support for MySQL and link the results of database queries to Web pages. You'll get full details on PHP programming and MySQL database development, and then you'll learn to use these two cutting-edge technologies together. Easy-to-follow sample applications include a PHP online shopping cart, a MySQL order tracking system, and a PHP/MySQL news publishing system.

Read more, or grab your copy now!


previous page more like this  print this article  next page
 
Search...
 
In trog...
Logging With PHP
Building A Quick-And-Dirty PHP/MySQL Publishing System
Output Buffering With PHP
Date/Time Processing With PHP
Creating Web Calendars With The PEAR Calendar Class
more...
 
In the hitg report...
Crime Scenes
Animal Attraction
Lord Of The Strings
more...
 
In boombox...
Patience - George Michael
Think Tank - Blur
My Private Nation - Train
more...
 
In colophon...
Hostage - Robert Crais
The Dead Heart - Douglas Kennedy
Right As Rain - George Pelecanos
more...
 
In cut!...
American Chai
The Core
Possession
more...
 
Find out how you can use this article on your own Web site!


Copyright © 1998-2018 Melonfire. All rights reserved
Terms and Conditions | Feedback