How To Escape Multi-Dimensional Array Data in PHP

Came across an interesting problem recently building a web app for a client where I had a multi-dimensional array coming through via the $_POST data.

Of course to use this in your PHP code you should first filter it to protect against SQL injection attacks and XSS script attacks.

I came across this code from corprocat.com. A good start, but it wasn’t quite what I needed. Specifically I wanted to filter multi-dimensional arrays of N levels.

Here’s my modified version:

function filterData($data) {
	if (is_array($data)) {
		foreach ($data as $elem) {
			filterData($elem);
		}
	} else {
		$data = trim(htmlentities(strip_tags($data)));
		if (get_magic_quotes_gpc())
			$data = stripslashes($data);
 
		$data = mysql_real_escape_string($data);
	}
 
    return $data;
}

Feel free to use it in your PHP web apps to escape multi-dimensional array data.

About Josh Kohlbach

Josh is a programmer, entrepreneur and the founder of Code My Own Road. He started this website to help programmers with business stuff and also to get things straight in his head. You can read more about Code My Own Road and Josh on the About page
No comments yet.

Leave a Reply

Read more:
Generate Cheap Marketing Ideas
Figure Out Dozens Of Cheapskate Marketing Ideas In Less Than 10 Minutes

I wanted to share with you a technique I've been doing for figuring out cheapskate marketing ideas. I've been doing...

Close