PHP – Prevent SQL Injection Attacks

The function below can be used to parse a string and format it ready to be used in an SQL query.  This will add slashes and escape as appropriate to help prevent SQL injection attacks.

function sql_quote($value) {
	if (get_magic_quotes_gpc()) {
		$value = stripslashes($value);
	}

	//check if this function exists
	if (function_exists('mysql_real_escape_string')) {
		$value = mysql_real_escape_string($value);
	}

	//for PHP version < 4.3.0 use addslashes
	else {
		$value = addslashes($value);
	}

	return $value;
}

Source: http://www.askbee.net/articles/php/SQL_Injection/sql_injection.html

/Zen

Leave a Reply

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

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>