Page 1 of 1

htmlentities() will not work with my array

Posted: Thu Jan 22, 2009 9:42 pm
by frank_mark
Hi guys,
I am trying to write a function that will take an array of strings and clean them up for secure input into the database.
So fa I have as follows:

Code: Select all

<?php
    function safe_input($params)
    {
        if(is_array($params))
        {
            foreach($params as $key => $string)
            {
                $string = clean_string($string);
            }
        }
        else // just checks whether it is a simple string as opposed to an array
        {
            $params = clean_string($params);
        }   
        return $params;     
    }
    
    function clean_string($string)
    {
        $string = trim($string);
        $string = strip_tags($string);
        $string = htmlentities($string, ENT_QUOTES);
        return $string;
    }
 
 
$s = array('aaa' => 'Me & you', 'bbb' =>"Liz's stuff is boring", 'ccc' => 'One & two');
 
print_r(safe_input($s));
?>
The odd thing is that it will clean the string perfectly. Yet somehow when i print the array the strings are back to normal, and by that I mean that the '&' will be uncoded.

It somehow gets messed up when the strings are finally returned to the array.

Any ideas??

Re: htmlentities() will not work with my array

Posted: Thu Jan 22, 2009 9:45 pm
by nor0101
Might have something to do with this:

(from php.net foreach documentation)

"Note: Unless the array is referenced, foreach operates on a copy of the specified array and not the array itself... "

Re: htmlentities() will not work with my array

Posted: Thu Jan 22, 2009 10:12 pm
by frank_mark
ah, thanks for that Connor.

I'll look into it. I thought I had left references behind with other languages. I guess not.

Re: htmlentities() will not work with my array

Posted: Thu Jan 22, 2009 10:32 pm
by requinix
By "array is referenced" they mean this (only PHP 5):

Code: Select all

foreach($params as $key => &$string)
Otherwise you have to update the array:

Code: Select all

$params[$key] = clean_string($string);

Re: htmlentities() will not work with my array

Posted: Fri Jan 23, 2009 12:57 am
by frank_mark
Thank you kindly gents. The reference tips worked brilliantly.