当前位置: 首页 > 网络学院 > 服务端脚本教程 > PHP > mysql_real_escape_string() 函
PHP 中的 mysql_real_escape_string() 函
出处:互联网 整理: 软晨网(RuanChen.com) 发布: 2009-03-04 浏览: 239 ::
The mysql_real_escape_string() function escapes special characters in a string for use in an SQL statement
mysql_real_escape_string()函数的作用是:转义 SQL 语句中使用的字符串中的特殊字符,并考虑到连接的当前字符集。
The following characters are affected:
可对下列字符进行操作:
This function returns the escaped string on success, or FALSE on failure.
如果函数执行成功,将返回转义后的字符串;如果执行失败将返回False。
mysql_real_escape_string(string,connection) |
| Parameter参数 | Description描述 |
|---|---|
| string | Required. Specifies the string to be escaped 必要参数。制定需要执行转义操作的字符串 |
| connection | Optional. Specifies the MySQL connection. If not specified, the last connection opened by mysql_connect() or mysql_pconnect() is used. 可选参数。指定MySQL连接。如果不指定该参数,那将默认使用通过mysql_connect()函数或mysql_pconnect()函数最后一次打开的连接 |
Note: Use this function to prevent database attack!
注意:可以使用该函数来阻止数据库被攻击。
<?php
$con = mysql_connect("localhost", "peter", "abc123");
if (!$con) { die('Could not connect: ' . mysql_error()); } // some code to get username and password // escape username and password for use in SQL $user = mysql_real_escape_string($user); $pwd = mysql_real_escape_string($pwd)); $sql = "SELECT * FROM users WHERE user='" . $user . "' AND password='" . $pwd . "'" // more code mysql_close($con); ?> |
Database attack. This example demonstrates what could happen if we do not use the mysql_real_escape_string() function on the username and password:
下面将列举数据库被攻击的状况。这个案例演示了如果我们在不输入用户名和密码并使用mysql_real_escape_string()函数的情况下将会发生什么:
<?php
$con = mysql_connect("localhost", "peter", "abc123");
if (!$con) { die('Could not connect: ' . mysql_error()); } $sql = "SELECT * FROM users
WHERE user='{$_POST['user']}'
AND password='{$_POST['pwd']}'";
mysql_query($sql); // We didn't check username and password. // Could be anything the user wanted! Example: $_POST['user'] = 'john'; $_POST['pwd'] = "' OR ''='"; // some code mysql_close($con); ?> |
The SQL sent would be:
发送的SQL将会是如下信息:
SELECT * FROM users WHERE user='john' AND password='' OR ''='' |
This means that anyone could log in without a valid password!
上述代码意味着任何人都不能通过无效的密码登陆。
The correct way to do it to prevent database attack:
防止数据库被攻击的正确做法如下:
<?php
function check_input($value)
{
// Stripslashes
if (get_magic_quotes_gpc()) { $value = stripslashes($value); }
// Quote if not a number
if (!is_numeric($value)) { $value = "'" . mysql_real_escape_string($value) . "'"; }
return $value;
} $con = mysql_connect("localhost", "peter", "abc123");
if (!$con) { die('Could not connect: ' . mysql_error()); } // Make a safe SQL $user = check_input($_POST['user']); $pwd = check_input($_POST['pwd']); $sql = "SELECT * FROM users WHERE user=$user AND password=$pwd"; mysql_query($sql); mysql_close($con); ?> |
评论 (0) All