Can't get this recursive function working...

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Sander
Forum Commoner
Posts: 38
Joined: Sat Aug 06, 2005 12:43 pm

Can't get this recursive function working...

Post by Sander »

I've been working on a function that's supposed to clean a variable/array from any evil code, but I can't get it to work.

If I use the function with an array, I always get the same thing back. This is the first time that I try to create a recursive function, so it probably has something to do with that.

Anyway, the function:

Code: Select all

/**
	* @return mixed
	* @param mixed $data
	* @desc Clear a variable from evil code. If it's an array, clean all keys in the array (recursive)
	*/
	function clean_var($data)
	{
		if(is_array($data))
		{
			//---
			// Array
			//---

			// move through each element
			while(list($k, $v) = each($data))
			{
				// recurse
				$data[$k] = $this->clean_var($v);
			}
		}
		else
		{
			//---
			// Normal variable
			//---

			// get rid of slashes
			if(get_magic_quotes_gpc())
				$data = stripslashes($data);
				
			// clean
			$data = htmlspecialchars(urldecode($data), ENT_QUOTES);
			$data = str_replace('(', '(', $data);
			$data = str_replace(')', ')', $data);
		}

		// return
		return $data;
	}
I was also wondering if I'm cleaning the string good enough; should I check for anything else?
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

looking at your code, it appears to be a method, correct?

Code: Select all

function clean_var($data)
{
  if(is_array($data))
  {
    return array_map(array($this,__FUNCTION__),$data);
  }
  else
  {
    return str_replace(array('(',')'),array('(',')'),htmlspecialchars(urldecode($data),ENT_QUOTES)); 
  }
}
try that.
Sander
Forum Commoner
Posts: 38
Joined: Sat Aug 06, 2005 12:43 pm

Post by Sander »

Whoops, the function was already working, seems I was just doing a really stupid thing; I was using it like this:

Code: Select all

clean_var($array);
print_r($array);
Instead of:

Code: Select all

$array = clean_var($array);
print_r($array);
My bad... heh.

Still, I improved the function using some of your code. Thanks :)
Post Reply