View Single Post
Old 01-04-2006, 12:14 AM   PM User | #1
Velox Letum
Senior Coder

 
Join Date: Apr 2005
Location: Colorado, United States
Posts: 1,208
Thanks: 0
Thanked 0 Times in 0 Posts
Velox Letum is an unknown quantity at this point
Automatic $_POST Variable Escaping

On a few of my sites, I use a small snippit of code to automatically escape all $_POST variables (also $_GET variables) to be safe to use in MySQL queries. It's made up of two parts. The first is the code that checks to see if $_POST (or $_GET) is empty; second is the escaping function which either uses array_walk_recursive() or array_map() depending on your PHP version.

Also, a word of warning. mysql_real_escape_string() requires an active MySQL connection to function, so be sure to place the variable check snippit after your database connection string.

Variable check:
PHP Code:
if (!empty($_POST) && is_array($_POST)) {
    
recurse_escape_mysql($_POST);

recurse_escape_mysql():
PHP Code:
function recurse_escape_mysql(&$var$key NULL){
    if (
function_exists('array_walk_recursive')) {
        if(
is_array($var)){ 
            
array_walk_recursive($var'recurse_escape_mysql');
        } else {
            if (
get_magic_quotes_gpc()) {
                
$var stripslashes($var); 
            }
            
$var mysql_real_escape_string($var);
        }
    } else {
        if(
is_array($var)){ 
            
$var array_map('recurse_escape_mysql'$var); 
        } else {
            if (
get_magic_quotes_gpc()) {
                
$var stripslashes($var);
            }
            
$var mysql_real_escape_string($var);
        } 
        return 
$var;
    }

__________________
"$question = ( to() ) ? be() : ~be();"

Last edited by Velox Letum; 01-04-2006 at 04:25 AM..
Velox Letum is offline   Reply With Quote