Validating $_GET vars (PHP)

I've seen this before in a lot of people's code and I'm not going to lie, I've done this too...not validating $_GET vars.

When most developers develop scripts that take in $_GET like this:

www.example.com/thing.php?id=1

When you look at the scripting side developers may just enter the $_GET['id'] var plainly into the script like this:

  1. <?php
  2. $query = "SELECT * FROM example WHERE id = "'.$_GET['id'].'"";
  3. ?>

Well that is unsafe...

You have to validate these $_GET vars, most beginner PHP developers often make this mistake and in some PHP books its scary how they don't teach to validate $_GET vars.

Here is an example of how to validate a $_GET that should be validated as an integer:

We have www.example.com/thing.php?id=1 again.

  1. <?php
  2. //we should validate like so...
  3.  
  4. if (!isset($_GET['id'])) {
  5.         //give error message or...
  6.         return;
  7. } else {
  8.         if ($_GET['id'] == '') {
  9.                 //give error message or...
  10.                 return;
  11.         }
  12.        
  13.         if (!is_numeric($_GET['id'])) {
  14.                 //give error message or...
  15.                 return;
  16.         }
  17. }
  18. ?>

What we did there is:
1) Make sure the variable is set.
2) Make sure the variable is not empty or NULL.
3) Make sure the variable is of an numeric value, because we are getting IDs(in this case are strictly numeric).

Another way...put it into a function for easier code reuse if you need to validate multiple numeric $_GET vars:

  1. <?php
  2. function validate_get_int($var) {
  3.         if (!isset($var)) {
  4.                 //give error message or...
  5.                 return;
  6.         } else {
  7.                 if ($var == '') {
  8.                         //give error message or...
  9.                         return;
  10.                 }
  11.                
  12.                 if (!is_numeric($var)) {
  13.                         //give error message or...
  14.                        return;
  15.                 }
  16.         }
  17. }
  18. ?>

There we have it...validated $_GET vars. You can also apply this to any data type your $_GET vars contain for validation (int, string, double, etc).

Enjoy,
Rashaud Teague