Home > php教程 > php手册 > body text

php 防止sql注入的有效处理方法

WBOY
Release: 2016-05-25 16:41:02
Original
1771 people have browsed it

为了数据安全,防止注入需要过滤$_GET获得的字符串,一开始我还自已写过滤的函数,后来看到php自带的一个过滤函数,所以把addslashes推荐给大家.

一个使用 addslashes() 的例子是当你要往数据库中输入数据时,例如,将名字 O'reilly插入到数据库中,这就需要对其进行转义,大多数据库使用作为转义符:O'reilly,这样可以将数据放入数据库中,而不会插入额外的,当 PHP 指令 magic_quotes_sybase 被设置成 on 时,意味着插入 ' 时将使用 ' 进行转义.

例子:mysql和php自带很多函数可以处理字符问题,下面给出几个会经常用到的.

ps:由于php6开始不支持magic_quotes_gpc,所以下面的东西都是假设在magic_quotes_gpc=off的条件上(不知道php6会出什么新东西....)

mysql_real_escape_string()

定义:函数转义 SQL 语句中使用的字符串中的特殊字符。

语法: mysql_real_escape_string(string,connection)

说明:本函数将 string 中的特殊字符转义,并考虑到连接的当前字符集,因此可以安全用于本函数将 string 中的特殊字符转义,并考虑到连接的当前字符集,因此可以安全用于mysql_query()。

数据库攻击,本例演示如果我们不对用户名和密码应用 mysql_real_escape_string() 函数会发生什么:

<?php 
	$con = mysql_connect("localhost", "hello", "321"); 
	if (!$con) 
	  { 
	  die(&#39;Could not connect: &#39; . mysql_error()); 
	  } 
	 
	$sql = "SELECT * FROM users 
	WHERE user=&#39;{$_POST[&#39;user&#39;]}&#39; 
	AND password=&#39;{$_POST[&#39;pwd&#39;]}&#39;"; 
	mysql_query($sql); 
	//开源代码phprm.com 
	// 不检查用户名和密码 
	// 可以是用户输入的任何内容,比如: 
	$_POST[&#39;user&#39;] = &#39;john&#39;; 
	$_POST[&#39;pwd&#39;] = "&#39; OR &#39;&#39;=&#39;"; 
	 
	// 一些代码... 
	 
	mysql_close($con); 
	 
Copy after login

那么 SQL 查询会成为这样:

SELECT * FROM users WHERE user='john' AND password='' OR ''=''这意味着任何用户无需输入合法的密码即可登陆.

addSlashes()

定义:addslashes() 函数在指定的预定义字符前添加反斜杠。

语法:addslashes(string)

注释:默认情况下,PHP 指令 magic_quotes_gpc 为 on,对所有的 GET、POST 和 COOKIE 数据自动运行 addslashes()。不要对已经被 magic_quotes_gpc 转义过的字符串使用addslashes(),因为这样会导致双层转义,遇到这种情况时可以使用函数.

get_magic_quotes_gpc() 进行检测,由于实例代码过长,给出函数解释链接,相关函数:

<?php 
	   $str = "Is your name O&#39;reilly?"; 
	   //开源代码phprm.com 
	   // 输出:Is your name O&#39;reilly? 
	   echo addslashes($str); 
	   
Copy after login

StripSlashes()去掉反斜线字符,stripslashes() 函数删除由 addslashes() 函数添加的反斜杠.

语法:stripslashes(string)

<?php 
	echo stripslashes("Who&#39;s John Adams?"); 
	 
Copy after login

本文地址:

转载随意,但请附上文章地址:-)

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!