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 post helpful, or at least, interesting?