Snippet: encode

January 19, 2009
Tags: snippets, php
What's the point of having a blog if you don't share your favorite little tricks? SQL injection is a common security vulnerbility that developer's face with any site that accepts user generated content. This is a small function I use to help prevent that. It's not full-proof, you still need to do error checking on all variables that user's can manipulate, but this just make's life easier.
/**
 * encode - encode's user generated content to help prevent SQL injection
 *
 * Corey Hart @ http://www.codenothing.com
 * January 19, 2008
 */ 

function encode($obj){
	if (is_array($obj)){
		foreach ($obj as $key => $value){
			$obj[$key] = (is_array($value)) ? encode($value) : htmlspecialchars($value, ENT_QUOTES);
		}
	}else{
		$obj = htmlspecialchars($obj, ENT_QUOTES);
	}

	// Return the encoded object
	return $obj;
}

$_GET = encode($_GET);
$_POST = encode($_POST);
Have a question or comment? ask@codenothing.com.