Page 1 of 1

Foreach Loop Fails

Posted: Mon Apr 07, 2008 5:41 pm
by ykarmi
Hey Guys,
I wrote this PHP to clean up data before i enter it into a mysql database
This is the code:

Code: Select all

function mysql_sanitize($input){
    //Cleans the input for proper mysql_insertion
    function specific_input_sanitize($input){
        if(get_magic_quotes_gpc()){ $input = stripslashes($input);}
        $input = mysql_real_escape_string($input);
        $input .= "_sanitized";
        return $input;
    }
    
    /*
    If the input is an array: loop through all its values:
        1) If the value is also an array: loop through all of its values and sanitize each
        2) If not an array: sanitize value
    If not an array: loop through all of its values and sanitize each
    */
    
    if(is_array($input)){
        foreach($input as $key => $value){
            if(is_array($value)){
                foreach($value as $nested_key => $nested_value){
                    $value[$nested_key] = specific_input_sanitize($nested_value);
                }
            }else{
                $input[$key] = specific_input_sanitize($value);
            }
        }
    }else{
        $input = specific_input_sanitize($input);
    }
    return $input;
}
I am planning on using this function to clean up a whole $_POST variable.
In a case where I have a group of checkboxes in an html form, the selected ones will be sent as an array to php.

Possible returned $_POST data could look like this

Code: Select all

Array
(
 
    [title_header] => sample_header_sanitized
    [information_header] => sample_info_sanitized
    [files_background] => sample_bg_sanitized
 
 [features] => Array
        (
            [0] => header
            [1] => background
            [2] => banner
            [3] => external_banner
            [4] => contact_box
        )
)
As you can see the cleans everything up perfectly (notice the _sanitized after every element's value?) until it comes accross one of those arrays. The loop seems to fail to clean up the contents of that array and I cannot find a possible explanation to why this would happen. Could you please take a look at it?
Thanks :D,
Yuval

Re: Foreach Loop Fails

Posted: Tue Apr 08, 2008 3:53 am
by EverLearning
Unless the array is referenced(available in PHP5), foreach operates on a copy of the specified array and not the array itself, so assigning to $value[$nested_key] in your example wont work.

Instead of

Code: Select all

$value[$nested_key] = specific_input_sanitize($nested_value);
try this.

Code: Select all

$input[$key][$nested_key] = specific_input_sanitize($nested_value);