代码改变世界

PHP+mysql防止SQL注入

2021-06-26 12:41  天心PHP  阅读(183)  评论(0编辑  收藏  举报

应对方法:

1.mysql_escape_string() 转义特殊字符((PHP 4 >= 4.3.0, PHP 5))(mysql_real_escape_string必须先链接上数据库,否则会报错)

下列字符受影响:

\x00 //对应于ascii字符的NULL
\n  //换行符且回到下一行的最前端
\r //换行符
\ //转义符
'
"
\x1a  //16进制数

如果成功,则该函数返回被转义的字符串。如果失败,则返回 false。

2.addslashes(): 函数返回在预定义字符之前添加反斜杠的字符串 (stripslashes()实现字符串还原)

预定义的字符有:

单引号('
    双引号("
    反斜杠(\)
    NULL

3.prepared  statements(预处理机制)

<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
 echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
/* Non-prepared statement */
if (!$mysqli->query("DROP TABLE IF EXISTS test") || !$mysqli->query("CREATE TABLE test(id INT)")) {
 echo "Table creation failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
/* Prepared statement, stage 1: prepare */
if (!($stmt = $mysqli->prepare("INSERT INTO test(id) VALUES (?)"))) {
 echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
/* Prepared statement, stage 2: bind and execute */
$id = 1;
if (!$stmt->bind_param("i", $id)) {
 echo "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error;
}
if (!$stmt->execute()) {
 echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
}
?>