Tuesday, July 28, 2009

Escaping Data Structures

As we all know, to protect against SQL injection and snafus caused by single quotes in your data, always escape your inputs before running queries. However, what happens when your input is a complex data structure, such as an object, an array of objects, or an array of objects that in turn contain arrays of objects? Running foreach statements and escaping each individual value can result in very long functions, which accomplish basically the same thing (escape all values) but with different named variables and data types. Running mysqli::real_escape_string on the occasional single-dimension function parameter is fine, but for complicated data structures, you should farm out the work to a function.

I have written just such a function as part of my Database class, and it works like a charm:


/**
* Function to run real_escape_string recursively on an object or array.
*
* @param mixed &$source The object or array to escape.
*
* @access private
* @return null
*/
private function _escape(&$source)
{
foreach ($source as &$var) {
if (is_array($var) || is_object($var)) {
$this->_escape($var);
} else {
$var = $this->_mysqli->real_escape_string($var);
}
}
}

No comments:

Post a Comment