PHP SQL Injection – POST/GET Protection

A common issue arising in any PHP website is how to protect against SQL injection. One of the simplest and most efficient way to protect against a huge range of SQL injection attacks is to filter all POST and GET values before executing any other code. Include this piece of code at the beginning of each of your php files (either by saving it as security.php and then including it, or by including the code into one of your top level includes), and you will save yourself from a lot of headaches. You will still need to keep an eye out for other SQL injection opening on your website – but you will not have to worry anymore about SQL code that might sneak in through your GET and POST variables.

The function secure_array will also help you secure any data array that you have against SQL injection attacks (and the neat thing is it works for any n-dimensional array). There is one thing that you need to set up in order to make this work, and that is replacing the $mysqli -> real_escape_string() function with an equivalent one depending on which database connector you are using (mysql, PDO, etc.).

	function secure_array(&$array)
	 // this function secures the content of an array against SQL injection and HTML code injection attacks
	 // it works for arrays of any number of dimensions, recursively for each dimension

	 if (isset($array))
		 foreach ($array as $key => $value)
			  if (is_array($array[$key])) // if element is array, then go to next dimension
			  else // if element is a normal variable, clean it up
			   $array[$key] = $mysqli -> real_escape_string($array[$key]); // replace this with mysql / PDO real escape string function depending on which database connector you are using
			   $array[$key] = strip_tags($array[$key]);


	secure_array($_POST); // clean up $_POST variables
	secure_array($_GET); // clean up $_GET variables

One Response to PHP SQL Injection – POST/GET Protection

  1. Oliver Russell says:

    It is also possible to prevent php sql injection ( ) attacks by authenticating user’s input for a definite set of rules for syntax, type and length.

Leave a Reply

Your email address will not be published. Required fields are marked *

five × 2 =

This site uses Akismet to reduce spam. Learn how your comment data is processed.

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.