简体   繁体   English

PHP SQL注入保护

[英]Php sql injection protection

I am using mysql_real_escape_string($_REQUEST['page']) in my code. 我在代码中使用mysql_real_escape_string($ _ REQUEST ['page'])。 Is it able to prevent SQL Injection in my php code else i will have to do more protection ? 是否可以防止在我的PHP代码中进行SQL注入,否则我将不得不做更多的保护?

Thanks 谢谢

是的,但准备好的陈述会更好。

Personally, I would drop the mysql extension and migrate to the mysqli extension. 就个人而言,我将删除mysql扩展名并迁移到mysqli扩展名。 The problem with the mysql extension is that its old, and quite frankly, its rather easy to forget to escape something. mysql扩展的问题在于它很旧,坦率地说,它很容易忘记转义。

mysqli has support for prepared statements and it also has an OOP API which makes it way easier to develop. mysqli支持预备语句 ,并且还具有OOP API,这使得开发起来更容易。

When you start using prepared statements , it makes it easier to keep track of your parameters. 当您开始使用准备好的语句时 ,可以更轻松地跟踪参数。 It also auto escapes them for you. 它还会自动为您转义。

I would also recommend using prepared statements in most cases, but it's only necessary when inserting data that came from a user that could be a string. 我还建议在大多数情况下使用准备好的语句,但这仅在插入来自用户的数据(可能是字符串)时才是必需的。 Prepared statements are more expensive (performance), so when you can avoid them you probably should. 预备语句更昂贵(性能),因此,当您可以避免使用它们时,应该选择。 There are many benefits of using prepared statements and/or database transactions. 使用准备好的语句和/或数据库事务有很多好处。 You should probably look into it, unless you already have. 除非已经拥有,否则您可能应该调查一下。

If you receive numerical values from, for example, a form, you just need to ensure data quality by converting the input into a number (any input from GET or POST are ALWAYS regarded as strings by PHP, unless you convert them), and any malicious code will be removed. 如果您从某种形式接收数值,则只需要通过将输入转换为数字来确保数据质量(除非将它们转换,否则GET或POST的任何输入都会被PHP视为字符串),以及恶意代码将被删除。

Here's an example: 这是一个例子:

$intCarAge = (int) $_POST['car_age'];
mysqli_query("UPDATE cars SET car_age = " . $intCarAge . " WHERE id = '123' ");

The "(int)" converts the data in the input variable $_POST['car_age'] to a number (integer). “(int)”将输入变量$ _POST ['car_age']中的数据转换为数字(整数)。 It can be added before any variable in your code. 可以将其添加到代码中的任何变量之前。 Any letters inside the variable will be removed and any numbers will be kept. 变量中的所有字母将被删除,并且所有数字将被保留。 You can read more about number conversion here. 您可以在此处阅读有关数字转换的更多信息。

Hope I was of any help! 希望我有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM