My Favorite Way of Validating Form Inputs in PHP

| No TrackBacks
I received a few great blog comments in response to my post on Updating my Mobile Blog Portal to Support Multiple URL Patterns (m.php?a=1 vs m.php/1).  The general question in each of these comments was, "so what is your preferred, or favorite, way of validating form inputs in PHP?"  Good question.

When I don't have access to PHP 5.2 or later, I'm unable to take advantage of PHP's filter_input_array() validation mechanism.  That's OK though, because there's nothing like validating form inputs the hard-way.  When validating form inputs manually, without the use the of any specialized helper functions, I think it's hard to do much better than a nice combination of isset, preg_replace, preg_match, and empty.

Imagine you're writing an AJAX controller and are expecting a GET with a 7-digit number and a string of only alpha characters in the URI:  controller.php?id=1234567&field=status.  Simple enough:

<?php

$id = (isset($_GET['id'])) ?
preg_replace("/\D/","",$_GET['id']) : null;
if( empty($id) || preg_match("/^\d{7}$/",$id)!==1 ) {
// Validation of $id failed. It was either empty or wasn't
// exactly 7-digits like you were expecting.
}

$field = (isset($_GET['field'])) ?
preg_replace("/[^a-z]/","",$_GET['field']) : null;
if( empty($field) ) {
// Validation of $field failed. It was either empty or didn't
// contain any alpha characters.
}

?>

In your AJAX controller, say you need to read a command, regardless of the HTTP request method.  The command tells the AJAX controller what needs to be done.  Here's how you might read and validate a command received from either a GET or a POST:

<?php

define("GET","GET");
define("POST","POST");

try {

// Get the method we're processing, it's either a GET or a POST.
// This controller doesn't support PUT or DELETE.
$method = (isset($_SERVER['REQUEST_METHOD'])) ?
$_SERVER['REQUEST_METHOD'] : null;
if( empty($method) || ($method !== GET && $method !== POST) ){
throw new Exception("Unsupported HTTP method type: " . $method);
}

// Get the AJAX command we need to process stored
// in the 'ajax' variable.
$cmd = null;
if( $method === GET ) {
$cmd = ( isset($_GET['ajax'])) ? $_GET['ajax'] : null;
}
else if ( $method === POST ) {
$cmd = isset($_POST['ajax']) ? $_POST['ajax'] : null;
}

if( empty($cmd) ) {
throw new Exception("Unknown command!");
}

// Switch here on the command and actually do some work.

}
catch ( Exception $e ) {
echo "ERROR: " . $e->getMessage();
}

?>

So, there ya go.  In pretty much any PHP web-app I've written, I use this approach to validate incoming commands and arguments.  Enjoy.

Did You Find this Helpful?

Did you find this post helpful, or at least, interesting?

  

Send Mark a Direct Message

If you'd like to send me a direct message, please do so below. However, I do not publicly post comments or messages submitted directly to me. So, if you're going to try to SPAM me, or my blog, you're pretty much wasting your time.

400 characters remaining

Error

About Mark

A Silicon Valley native, Mark Kolich is a full-time Software Engineer, a casual entrepreneur, and a consultant for hire. A web technologies expert, his current focus is on building powerful and robust cloud-driven web-applications using Java, PHP, Perl, AJAX, DHTML, CSS, and JavaScript. His favorite programming languages are PHP, Java and JavaScript. He uses Linux, enjoys biking to work, loves building great software, and always writes elegant, readable, and maintainable code.

No TrackBacks

No trackbacks attached to this entry.

Twitter (@markkolich)

Translate

About this Entry

This page contains a single entry by Mark Kolich published on August 21, 2009 10:30 AM.

My First Tic-Tac-Toe Game was the previous entry in this blog.

Mount San Gorgonio: Hike To the Summit and Back in a Single Day is the next entry in this blog.

Find recent content on the main index or look in the archives to find all content.