Deprecated: Function ereg() is deprecated in /home3/vvaswani/db-mysql.php on line 174

Deprecated: Function split() is deprecated in /home3/vvaswani/public_html/community/columns/trog/article.php on line 101

Deprecated: Function eregi_replace() is deprecated in /home3/vvaswani/sql.php on line 301

Deprecated: preg_replace(): The /e modifier is deprecated, use preg_replace_callback instead in /home3/vvaswani/public_html/community/columns/trog/article.php on line 107

Deprecated: preg_replace(): The /e modifier is deprecated, use preg_replace_callback instead in /home3/vvaswani/public_html/community/columns/trog/article.php on line 109

Deprecated: Function ereg_replace() is deprecated in /home3/vvaswani/public_html/community/columns/trog/article.php on line 124

Deprecated: Function ereg_replace() is deprecated in /home3/vvaswani/public_html/community/columns/trog/article.php on line 125

Deprecated: Function split() is deprecated in /home3/vvaswani/public_html/community/columns/trog/article.php on line 127

Deprecated: Function ereg() is deprecated in /home3/vvaswani/db-mysql.php on line 174

Deprecated: Function ereg() is deprecated in /home3/vvaswani/db-mysql.php on line 174

Deprecated: Function ereg() is deprecated in /home3/vvaswani/db-mysql.php on line 174

Deprecated: Function ereg() is deprecated in /home3/vvaswani/db-mysql.php on line 174

Deprecated: Function ereg() is deprecated in /home3/vvaswani/db-mysql.php on line 174

Deprecated: Function ereg() is deprecated in /home3/vvaswani/db-mysql.php on line 174

Deprecated: Function ereg() is deprecated in /home3/vvaswani/db-mysql.php on line 174

Deprecated: Function ereg() is deprecated in /home3/vvaswani/db-mysql.php on line 174

Deprecated: Function ereg() is deprecated in /home3/vvaswani/db-mysql.php on line 174

Deprecated: Function ereg() is deprecated in /home3/vvaswani/db-mysql.php on line 174
The Melonfire Community - Trog
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.

| An Empty Vessel... |

This tutorial assumes that the user input to be validated arrives through a web form. This is not the only way a PHP script can get user data; however, it is the most common way. If your PHP application needs to validate command-line input, I'd recommend you read my article on the PEAR Console_Getopt class, available for your perusal at http://www.melonfire.com/community/columns/trog/article.php?id=259.

It's common practice to use client-side scripting languages such as JavaScript or VBScript for client-side form validation. However, this type of client-side validation is not foolproof. You're not in control of the client, so if a user turns off JavaScript in his or her browser, all your efforts to ensure that the user does not enter irrelevant data become - well - irrelevant. That's why most experienced developers use both client-side and server-side validation. Server-side validation involves checking the values submitted to the server through a PHP script, and taking appropriate action when the input is incorrect.

Let's begin with the most commonly found input error: a required form field that is missing its value. Take a look at this example:


<html>
<head></head>
<body>
<?php
if (!isset($_POST['submit'])) {
?>
    <form action = '<?php $_SERVER['PHP_SELF'] ?>' method = 'post'>
    Which sandwich filling would you like?
    <br />
    <input type = 'text' name = 'filling'>
    <br />
    <input type = 'submit' name = 'submit' value = 'Save'>
    </form>
<?php
}
else {
    // set database variables
    $host = 'localhost';
    $user = 'user';
    $pass = 'secret';
    $db = 'sandwiches';

    // get user input
    $filling = mysql_escape_string($_POST['filling']);

    // open connection
    $connection = mysql_connect($host, $user, $pass) or die('Unable to connect!');

    // select database
    mysql_select_db($db) or die('Unable to select database!');

    // create query
    $query = 'INSERT INTO orders (filling) VALUES ("$filling")';

    // execute query
    $result = mysql_query($query) or die("Error in query: $query. ".mysql_error());

    // close connection
    mysql_close($connection);

    // display message
    echo "Your {$_POST['filling']} sandwich is coming right up!";
}
?>
</body>
</html>


It's clear from the example above that submitting the form without entering any data will result in an empty record being added to the database (assuming no NOT NULL constraints on the target table). To avoid this, it's important to verify that the form does, in fact, contain valid data, and only then perform the INSERT query. Here's how:


<html>
<head></head>
<body>
<?php
if (!isset($_POST['submit'])) {
?>
    <form action = '<?php $_SERVER['PHP_SELF'] ?>' method = 'post'>
    Which sandwich filling would you like?
    <br />
    <input type = 'text' name = 'filling'>
    <br />
    <input type = 'submit' name = 'submit' value = 'Save'>
    </form>
<?php
}
else {
    // check for required data
    // die if absent
    if (!isset($_POST['filling']) || trim($_POST['filling']) == '') {
        die("ERROR: You can't have a sandwich without a filling!");
    }
    else {
        $filling = mysql_escape_string(trim($_POST['filling']));
    }

    // set database variables
    $host = 'localhost';
    $user = 'user';
    $pass = 'secret';
    $db = 'sandwiches';

    // open connection
    $connection = mysql_connect($host, $user, $pass) or die('Unable to connect!');

    // select database
    mysql_select_db($db) or die('Unable to select database!');

    // create query
    $query = 'INSERT INTO orders (filling) VALUES ("$filling")';

    // execute query
    $result = mysql_query($query) or die("Error in query: $query. ".mysql_error());

    // close connection
    mysql_close($connection);

    // display message
    echo "Your {$_POST['filling']} sandwich is coming right up!";
}
?>
</body>
</html>


The error check here is both simple and logical: the trim() function is used to trim leading and trailing spaces from the field value, which is then compared with an empty string. If the match is true, the field was submitted empty, and the script dies with an error message before MySQL comes into the picture.

A common mistake, especially among newbies, is to replace the isset() and trim() combination with a call to PHP's empty() function, which tells you if a variable is empty. This isn't usually a good idea, because empty() has a fatal flaw: it'll return true even if a variable contains the number 0. The following simple example illustrates this:


<?php
// no data, returns empty
$data = '';
echo empty($data) ? "$data is empty" : "$data is not empty";
echo "<br />\n";

// some data, returns not empty
$data = '1';
echo empty($data) ? "$data is empty" : "$data is not empty";
echo "<br />\n";

// some data, returns empty
$data = '0';
echo empty($data) ? "$data is empty" : "$data is not empty";
?>


So, if your form field is only allowed to hold non-empty, non-zero data, empty() is a good choice for validating it. But if the range of valid values for your field includes the number 0, stick with the isset() and trim() combination instead.


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-
Strict Standards: mktime(): You should be using the time() function instead in /home3/vvaswani/public_html/community/columns/trog/article.php on line 731
2017 Melonfire. All rights reserved
Terms and Conditions | Feedback