Jump to content

Array_Walk to clean PHP arrays?


random1

Recommended Posts

I have the following code in a class called 'base':

 

/**
* Base::cleanArray()
* 
* @param mixed $value
* @return
*/
public function cleanArray($value)
{
	if (get_magic_quotes_gpc())
	{
		$value = stripslashes($value);
	}

	if (!is_numeric($value))
	{
		$value = mysql_real_escape_string($value);
	}

	return $value;
}

/**
* Base::cleanPhpArrays()
* 
* @return void
*/
public function cleanPhpArrays()
{
	array_walk($_GET, 'cleanArray');
	array_walk($_POST, 'cleanArray');
	array_walk($_COOKIE, 'cleanArray');

	extract($_GET,EXTR_PREFIX_ALL, 'get');
	extract($_POST,EXTR_PREFIX_ALL, 'post');
	extract($_COOKIE,EXTR_PREFIX_ALL, 'cookie');
}

 

This code is failing on the line: array_walk($_GET, 'cleanArray');

 

Warning: array_walk() [function.array-walk0]: Unable to call cleanArray() - function does not exist in ***********************\classes\base.php on line 1036

 

What syntax do I need to use for : array_walk($_GET, 'cleanArray'); ?

 

I've tried the following that do not work:

 

array_walk($_GET, '$this->cleanArray');

 

array_walk($_GET, '$this->cleanArray()');

 

array_walk($_GET, $this->'cleanArray');

Link to comment
https://forums.phpfreaks.com/topic/160740-array_walk-to-clean-php-arrays/
Share on other sites

Specifying callbacks in OOP is done depending on which context you are in: object context (there is a $this variable) or static context (there is no $this variable).

 

If there is a $this variable:

array_walk( $_GET, array( $this, 'cleanArray' ) );

 

If there is no $this variable:

array_walk( $_GET, 'Base::cleanArray' );

 

Also, it is wasteful to spend time cleaning $_GET, $_POST, $_COOKIE, etc. on each page request.  Not every page will use all three of them, so why clean things that won't be used?  You could write a "Getter" class for each one of them.  The "Getter" class will clean the object if it is the first time it has been requested.

 

Lastly, if you clean all of these values initially on page load, then you would have to unclean them determine what the original values where.  This may not be a problem for you, but there are times when you want to see the original, unaltered data for debugging purposes without the extra characters added by sanitizer functions.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.