The most comprehensive approach to preventing SQL injection
Release time: 2012-04-5 Views: 19361 Category: PHP tutorial
(1) mysql_real_escape_string--escapes special characters in strings used in SQL statements and takes into account the current character set of the connection
Here's how to use it:
- $sql = "SELECT COUNT (*) as Ctr from users where username
- = ' ". mysql_real_escape_string($username)."' and
- Password= ' ". mysql_real_escape_string($pw)." ' Limit 1 ';
mysql_real_escape_string()you can avoid any malicious SQL injection in user input by using a wrapper that is entered as a user.
(2) Open MAGIC_QUOTES_GPC to prevent SQL injection
There is a setting in php.ini: MAGIC_QUOTES_GPC = Off
This is off by default, and if it is turned on, it will automatically convert the query that the user commits to SQL.
For example, "switch to \" And so on, to prevent SQL injection has a major role.
If Magic_quotes_gpc=off, use the addslashes () function
(3) Custom functions
- function Inject_check($sql _str) {
- return eregi(' select|insert|and|or|update|delete|\ ' |\/\*|\*|\.\.\/|\.\/|union|into|load_file| OutFile ', $sql _str);
- }
- function verify_id($id=null) {
- if(! $id) {
- exit(' no submit parameter! ');
- } ElseIf(inject_check($id)) {
- exit(' argument submitted is illegal! ');
- } ElseIf(! Is_numeric($id)) {
- exit(' argument submitted is illegal! ');
- }
- $id = intval($id);
- return $id;
- }
- function Str_check( $str ) {
- if(! GET_MAGIC_QUOTES_GPC()) {
- $str = addslashes($str); //Filter
- }
- $str = str_replace("_", "\_", $str);
- $str = str_replace("%", "\%", $str);
- return $str;
- }
- function Post_check($post) {
- if(! GET_MAGIC_QUOTES_GPC()) {
- $post = addslashes($post);
- }
- $post = str_replace("_", "\_", $post);
- $post = str_replace("%", "\%", $post);
- $post = nl2br($post);
- $post = htmlspecialchars($post);
- return $post;
- }
The most comprehensive method of preventing SQL injection