The most comprehensive approach to preventing SQL injection

Source: Internet
Author: User
(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:

?

1

2

3

$sql= "select count(*)asctr from users where username

='".mysql_real_escape_string($username)."'and

password='". mysql_real_escape_string($pw)."'limit 1";

Use

Mysql_real_escape_string ()

As a wrapper for user input, you can avoid any malicious SQL injection in user input.

(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

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21st

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

functioninject_check($sql_str) {

returneregi('select|insert|and|or|update|delete|\'|\/\*|\*|\.\.\/|\.\/|union|into|load_file|outfile',$sql_str);

}

functionverify_id($id=null) {

if(!$id) {

exit('没有提交参数!');

}elseif(inject_check($id)) {

exit('提交的参数非法!');

}elseif(!is_numeric($id)) {

exit('提交的参数非法!');

}

$id= intval($id);

return$id;

}

functionstr_check( $str) {

if(!get_magic_quotes_gpc()) {

$str= addslashes($str);// 进行过滤

}

$str= str_replace("_","\_",$str);

$str= str_replace("%","\%",$str);

return$str;

}

functionpost_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 above describes the most comprehensive prevention of SQL injection methods, including aspects of the content, I hope that the PHP tutorial interested in a friend helpful.

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.