开发者

Php sql injection protection

I am using mysql_real_escape_string($_REQUEST['page']) in m开发者_如何学Goy code. Is it able to prevent SQL Injection in my php code else i will have to do more protection ?

Thanks


Yes, but prepared statements are better.


Personally, I would drop the mysql extension and migrate to the mysqli extension. The problem with the mysql extension is that its old, and quite frankly, its rather easy to forget to escape something.

mysqli has support for prepared statements and it also has an OOP API which makes it way easier to develop.

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.

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). 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!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜