如何安全地在MySQL数据库中插入代码

如何安全地在MySQL数据库中插入代码

本文介绍了如何安全地在MySQL数据库中插入代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在建立一个网站,用户可以在其中使用PHP和mySQL数据库存储代码段.但是我不知道如何安全地将用户输入的代码插入到我的数据库中.我无法使用通常使用的安全"功能(trimstripslashes等)来转换输入,因为重点是您可以查看在数据库中输入的代码.我已经看过my_real_escape_string(),但是我发现它不能转义%_,它们可以用作MySQL通配符.这会构成威胁吗?还是我可以只使用my_real_escape_string?提前感谢.

I'm building a website where users can store code snippets, using PHP and a mySQL database. But I can't figure out how to safely insert user inputed code into my database. I can't transform the input with the 'safety' functions I normally use (trim, stripslashes, etc.) because the whole point is that you can view the code as it's inputed in the database. I've looked at my_real_escape_string() but I saw that it does not escape the % and _, which can be used as MySQL wildcards. Does that pose a threat, or can I just use my_real_escape_string? Thanx in advance.

推荐答案

通配符仅在SELECT查询中使用时才生效,然后仅在使用某些功能时才生效.因此,对于插入代码,最好使用mysql_real_escape_string(),因为它们无效.

Wildcards only take effect when used in SELECT queries and then only when using certain functions. So for inserting the code it will be fine to use mysql_real_escape_string() as they will have no effect.

为使其更好,我建议您使用 PHP PDO ,以便可以使用参数绑定.以下示例来自 PHP手册:

To make it better I would recommend that you use PHPs PDO so that you can use parameter binding. The following example is from the PHP manual:

<?php
$stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (:name, :value)");
$stmt->bindParam(':name', $name);
$stmt->bindParam(':value', $value);

// insert one row
$name = 'one';
$value = 1;
$stmt->execute();

// insert another row with different values
$name = 'two';
$value = 2;
$stmt->execute();
?>

这篇关于如何安全地在MySQL数据库中插入代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-06 02:04