如何防止PHP中的代码注入攻击?

时间:2022-01-06 10:31:10

I am abot confusing, there are so many functions in PHP, and some using this, some using that. Some people use: htmlspecialchars(), htmlentities(), strip_tags() etc

我很困惑,PHP中有很多函数,有些用这个,有些用这个。有些人使用:htmlspecialchars()、htmlentities()、strip_tags()等

Which is the correct one and what do you guys usually use?

哪个是正确的,你们通常用什么?

Is this correct (advise me a better one, if any):

这是对的吗(如果有更好的建议的话):

$var = mysql_real_escape_string(htmlentities($_POST['username']));

This line can prevent MySQL injection and XSS attact??

这行可以防止MySQL注入和XSS attact吗?

Btw, is there any other things I need to pay attention beside XSS attack and MySQL injection?

顺便问一下,除了XSS攻击和MySQL注入,我还有什么需要注意的吗?

EDIT

编辑

To conclude:

结论:

If I want to insert string to database, I do not need to use htmlentities, just use the mysql_real_escape_string. When displaying the data, use htmlentities(), is that what you all mean??

如果我想将字符串插入数据库,我不需要使用htmlentities,只需使用mysql_real_escape_string。在显示数据时,使用htmlentities(),这是您所有的意思吗?

Summarize:

总结:

  • mysql_real_escape_string used when insert into database
  • 当插入到数据库时使用的mysql_real_escape_string
  • htmlentities() used when outputting data into webpage
  • htmlentities()用于将数据输出到网页中。
  • htmlspecialchars() used when?
  • htmlspecialchars函数()时使用?
  • strip_tags() used when?
  • strip_tags()时使用?
  • addslashes() used when?
  • addslashes()时使用?

Can somebody fill in the question mark?

有人能填上问号吗?

8 个解决方案

#1


59  

  • mysql_real_escape_string used when insert into database
  • 当插入到数据库时使用的mysql_real_escape_string
  • htmlentities() used when outputting data into webpage
  • htmlentities()用于将数据输出到网页中。
  • htmlspecialchars() used when?
  • htmlspecialchars函数()时使用?
  • strip_tags() used when?
  • strip_tags()时使用?
  • addslashes() used when?
  • addslashes()时使用?

htmlspecialchars() used when?

htmlspecialchars is roughly the same as htmlentities. The difference: character encodings.

htmlspecialchars与htmlentities大致相同。区别:字符编码。

Both encode control characters like <, >, & and so on used for opening tags etc. htmlentities also encode chars from other languages like umlauts, euro-symbols and such. If your websites are UTF, use htmlspecialchars(), otherwise use htmlentities().

两个编码控制字符,如<,>,&等用于打开标签等,htmlentities也从其他语言(如umlauts,欧元符号等)编码字符。如果您的网站是UTF,使用htmlspecialchars(),否则使用htmlentities()。

strip_tags() used when?

htmlspecialchars / entities encode the special chars, so they're displayed but not interpreted. strip_tags REMOVES them.

htmlspecialchars / entities对特殊字符进行编码,因此显示它们,但不解释它们。strip_tags删除它们。

In practice, it depends on what you need to do.

实际上,这取决于你需要做什么。

An example: you've coded a forum, and give users a text field so they can post stuff. Malicious ones just try:

例如:您编写了一个论坛,并为用户提供了一个文本字段,以便他们可以发布内容。恶意的试试:

pictures of <a href="javascript:void(window.setInterval(function () {window.open('http://evil.com');}, 1000));">kittens</a> here

If you don't do anything, the link will be displayed and a victim that clicks on the link gets lots of pop-ups.

如果你什么都不做,链接就会显示出来,点击链接的受害者会得到很多弹出窗口。

If you htmlentity/htmlspecialchar your output, the text will be there as-is. If you strip_tag it, it simply removes the tags and displays it:

如果您的输出是htmlentity/htmlspecialchar,那么文本将按原样存在。如果您对它进行strip_tag,它只需删除标记并显示它:

pictures of kittens here

Sometimes you may want a mixture, leave some tags in there, like <b> (strip_tags can leave certain tags in there). This is unsafe too, so better use some full blown library against XSS.

有时您可能需要混合,在其中保留一些标记,比如 (strip_tags可以在其中保留某些标记)。这也是不安全的,所以最好使用一些完整的库来对付XSS。

addslashes

To quote an old version of the PHP manual:

引用PHP手册的一个旧版本:

Returns a string with backslashes before characters that need to be quoted in database queries etc. These characters are single quote ('), double quote ("), backslash () and NUL (the NULL byte).

返回需要在数据库查询中引用的字符前有反斜杠的字符串。这些字符是单引号(')、双引号(")、反斜杠()和NUL(空字节)。

An example use of addslashes() is when you're entering data into a database. For example, to insert the name O'reilly into a database, you will need to escape it. It's highly recommeneded to use DBMS specific escape function (e.g. mysqli_real_escape_string() for MySQL or pg_escape_string() for PostgreSQL), but if the DBMS you're using does't have an escape function and the DBMS uses \ to escape special chars, you can use this function.

addslashes()的一个示例是当您将数据输入数据库时。例如,要将名称O'reilly插入数据库,您需要转义它。高度推荐使用DBMS特定的转义函数(例如,MySQL的mysqli_real_escape_string()或PostgreSQL的pg_escape_string())),但是如果您使用的DBMS没有转义函数,而且DBMS使用\来转义特殊的chars,您可以使用这个函数。

The current version is worded differently.

当前版本的措辞不同。

#2


5  

Only encode data at the point where it goes into the system it needs to be encoded for — otherwise you will run into situations where you want to manipulate the real data.

只在数据进入需要编码的系统时对其进行编码——否则您将遇到需要操作真实数据的情况。

For SQL injection - use bound variables as described in How can I prevent SQL injection in PHP? (it talks about prepared statements, but it is the binding that gives you protection, not the preparation).

对于SQL注入——使用绑定变量,如在PHP中如何防止SQL注入中所描述的那样?(它谈论的是事先准备好的陈述,但它是给你的保护,而不是准备)。

For XSS - if you are writing into HTML at point where either HTML or text is specified. Use htmlentities at the point where you generate your document. I would avoid storing the data in that form in the database (except possible in a write-rare-read-often system where CPU performance/disk access times were becoming and issue - then I would have a raw_ and an html_ version of the column … or just use memcached or similar).

对于XSS——如果您在指定HTML或文本的地方编写HTML。在生成文档的地方使用htmlentities。我将避免将数据以这种形式存储在数据库中(除了可能存在于CPU性能/磁盘访问时间变得异常频繁并发生问题的write-rare读系统中),然后我将拥有一个raw_和一个html_版本的列……或者仅仅使用memcached或类似的东西)。

If you are letting users enter URLs then you need to be more careful, as javascript:do_evil() is a valid URI that will execute (e.g. as an href for a clicked upon link or (in some browsers) the src of an image that is just loaded).

如果允许用户输入url,那么需要更加小心,因为javascript:do_evil()是一个有效的URI,它将执行(例如,作为单击的链接的href,或者(在某些浏览器中)刚刚加载的图像的src)。

#3


4  

I thought of this quick checklist:

我想到了这个简单的清单:

  • Always use HTTPS, without HTTPS your site is totally unencrypted. And no, client-side encrypting things and sending them won't work, think about it. Invalid HTTPS certificates also make you vulnerable to a MITM attack. Just use Let's Encrypt if you can't afford a certificate.
  • 总是使用HTTPS,没有HTTPS,你的网站完全没有加密。不,客户端加密和发送都不行,想想看。无效的HTTPS证书也使您容易受到MITM攻击。如果您负担不起证书,请使用Let's加密。
  • Always use htmlspecialchars() on any output from your PHP code, that is, or contains a user input. Most templating engines help you do that easily.
  • 总是在PHP代码的任何输出(即包含用户输入)上使用htmlspecialchars()。大多数模板引擎都可以帮助您轻松实现这一点。
  • Use HTTP-only flag in your php.ini to prevent scripts from accessing your cookies
  • 在php中使用仅http标志。ini防止脚本访问您的cookie
  • Prevent session-related problems
    • Never expose user's PHPSESSID (session ID) outside the cookie, if anybody gets to know a Session ID of somebody else, they can simply use it to login to their account
    • 不要将用户的PHPSESSID(会话ID)暴露在cookie之外,如果有人知道其他人的会话ID,他们可以使用它登录到自己的帐户
    • Be very careful with the Remember me function, show a little warning maybe.
    • 小心记住我的函数,可能会显示一些警告。
    • Refresh session ID when the user signs in (or whatever appropriate)
    • 当用户登录时刷新会话ID(或其他适当的方式)
    • Timeout inactive sessions
    • 超时不活跃的会议
  • 防止会话相关的问题永远不要将用户的PHPSESSID(会话ID)暴露在cookie之外,如果有人知道其他人的会话ID,他们可以简单地使用它登录到他们的帐户,使用Remember me函数要非常小心,可能会显示一些警告。当用户登录(或其他适当的)非激活会话超时时刷新会话ID
  • Never trust a cookie, it can be changed, removed, modified, and created by a script/user at any moment
  • 不要信任一个cookie,它可以随时被脚本/用户修改、删除、修改和创建
  • Prevent SQL-related problems
    • Always use prepared statements. Prepared statements causes the user input to be passed separately and prevents SQL Injection
    • 总是使用准备好的语句。准备语句导致用户输入被单独传递,并防止SQL注入
    • Make your code throw an exception when it fails. Sometimes your SQL server might be down for some reason, libraries like PDO ignore that error by default, and log a warning in the logs. This causes the variables you get from the DB to be null, depending on your code, this may cause a security issue.
    • 使您的代码在失败时抛出异常。有时,由于某些原因,您的SQL服务器可能会宕机,像PDO这样的库默认忽略这个错误,并在日志中记录一个警告。这将导致从DB获得的变量为null,这取决于您的代码,这可能导致安全问题。
    • Some libraries like PDO emulate prepared statements. Turn that off.
    • 有些库,如PDO,会模拟准备好的语句。关掉的。
    • Use UTF-8 encoding in your databases, it allows you to store virtually any character and avoid encoding-related attacks
    • 在数据库中使用UTF-8编码,可以存储几乎所有字符,避免与编码相关的攻击
    • Never concatenate anything to your query. Things like $myquery = "INSERT INTO mydb.mytable (title) VALUES(" . $user_input . ")" pretty much mean you have a huge security risk of an SQL injection.
    • 不要将任何内容连接到查询。$myquery = "插入到mydb中。(“mytable(标题)值。user_input美元。)“这几乎意味着SQL注入存在巨大的安全风险。”
  • 防止sql相关的问题总是使用准备好的语句。准备语句导致用户输入被单独传递,并防止SQL注入使代码在失败时抛出异常。有时,由于某些原因,您的SQL服务器可能会宕机,像PDO这样的库默认忽略这个错误,并在日志中记录一个警告。这将导致从数据库中获得的变量为null,这取决于您的代码,这可能会导致安全问题。有些库,如PDO,会模拟准备好的语句。将其关闭。在数据库中使用UTF-8编码,它允许您存储几乎任何字符,并且避免与编码相关的攻击,而不会将任何内容连接到您的查询。$myquery = "插入到mydb中。(“mytable(标题)值。user_input美元。)“这几乎意味着SQL注入存在巨大的安全风险。”
  • Store uploaded files in random, extension-less filenames. If a user uploads a file with .php file extension then whenever your code loads that file it executes it, and enables the user to execute some backend code
  • 以随机、无扩展的文件名存储上传的文件。如果用户上传了一个扩展名为.php的文件,那么无论何时您的代码加载它执行的文件,并且允许用户执行一些后端代码
  • Make sure you're not vulnerable to a CSRF attack.
  • 确保你不容易受到CSRF攻击。
  • Always update your PHP copy to ensure the latest security patches and performance improvements
  • 始终更新PHP副本,以确保最新的安全补丁和性能改进

#4


3  

You only need to use mysql_escape_string() when inserting into a database and htmlentites when displaying the HTML. This is sufficient if you want to prevent a simple injection attack, but there are no doubt many other security issues you should be aware of when developing a web app, another major one being cross site request forgeries.

当插入到数据库时,您只需要使用mysql_escape_string(),当显示HTML时则需要使用htmlentites。如果您想防止简单的注入攻击,那么这就足够了,但是毫无疑问,在开发web应用程序时,您应该意识到许多其他安全问题,另一个重要的问题是跨站点请求伪造。

#5


3  

htmlspecialchars() turns &, ', ", <, and > into an HTML entity format (&amp;, &quot;, etc.)

htmlspecialchars()将&、'、"、 <和> 转换为HTML实体格式(& '等)。

htmlentities() turns all applicable characters into their HTML entity format.

htmlentities()将所有适用的字符转换为其HTML实体格式。

strip_tags() removes all HTML and PHP tags.

strip_tags()删除所有HTML和PHP标记。

Both htmlspecialchars() and htmlentities() take an optional parameter indicating how quotation marks should be handled. See the PHP manual for specifics.

htmlspecialchars()和htmlentities()都接受一个可选参数,指示应该如何处理引号。有关详细信息,请参阅PHP手册。

The strip_tags() function takes an optional parameter indicating what tags should not be stripped.

函数的作用是:获取一个可选参数,指示哪些标签不应该被删除。

 $var = strip_tags ($var, '<p><br />');

The strip_tags() function will remove even invalid HTML tags, which may cause problems. For example, strip_tags() will yank out all of the code it thinks is an HTML tag, even if it’s improperly formed, like

strip_tags()函数甚至会删除无效的HTML标记,这可能会导致问题。例如,strip_tags()将删除它认为是HTML标记的所有代码,即使它的格式不正确。

<b I forgot to close the tag.

#6


2  

I wouldn't use htmlentities() when inserting data into the database or querying the database. If the data in you database is stored as entities, that data is then only useful to something that understands html entities.

在向数据库插入数据或查询数据库时,我不会使用htmlentities()。如果数据库中的数据存储为实体,那么该数据只对理解html实体的东西有用。

You have to use different escaping mechanisms for different types of output, e.g. SQL - mysql_real_escape_string(), HTML - htmlentities() or htmlspecialchars(), shell - escapeshellarg(). This is because the characters that are 'dangerous' are different for each one - there isn't a magic way you can make any data safe for any output medium.

您必须为不同类型的输出使用不同的转义机制,例如SQL - mysql_real_escape_string()、HTML - htmlentities()或htmlspecialchars()、shell - escapeshellarg()。这是因为“危险”字符对于每个字符都是不同的——没有一种神奇的方法可以使任何数据对任何输出介质都是安全的。

#7


1  

Take a look at this site PHP Security Consortium. I found it to be a good site for an overall overview on PHP Security (SQL Injection and XSS included).

看看这个网站PHP安全联盟。我发现它是一个很好的站点,可以对PHP安全性进行全面概述(包括SQL注入和XSS)。

#8


1  

I know it's an old question, but nowadays the most voted answer can be misleading for the beginners.

我知道这是一个老问题,但现在大多数投票的答案可能会误导初学者。

As of 2017

  1. You should never ever use mysql_real_escape_string. Even mysqli_real_escape_string is too weak to protect your database from the SQL injections. Instead of this, you should use PDO, and similar techniques. (see that guide)

    永远不要使用mysql_real_escape_string。甚至mysqli_real_escape_string也太弱了,无法保护数据库不受SQL注入的影响。相反,您应该使用PDO和类似的技术。(见指导)

  2. XSS (here I mean: strip_tags(), addslashes(), htmlspecialchars(), htmlentities()) - here the most voted answer is still correct, but I would suggest reading this article

    XSS(这里我的意思是:strip_tags()、addslashes()、htmlspecialchars()、htmlentities())——这里大多数投票的答案仍然是正确的,但是我建议阅读本文。

#1


59  

  • mysql_real_escape_string used when insert into database
  • 当插入到数据库时使用的mysql_real_escape_string
  • htmlentities() used when outputting data into webpage
  • htmlentities()用于将数据输出到网页中。
  • htmlspecialchars() used when?
  • htmlspecialchars函数()时使用?
  • strip_tags() used when?
  • strip_tags()时使用?
  • addslashes() used when?
  • addslashes()时使用?

htmlspecialchars() used when?

htmlspecialchars is roughly the same as htmlentities. The difference: character encodings.

htmlspecialchars与htmlentities大致相同。区别:字符编码。

Both encode control characters like <, >, & and so on used for opening tags etc. htmlentities also encode chars from other languages like umlauts, euro-symbols and such. If your websites are UTF, use htmlspecialchars(), otherwise use htmlentities().

两个编码控制字符,如<,>,&等用于打开标签等,htmlentities也从其他语言(如umlauts,欧元符号等)编码字符。如果您的网站是UTF,使用htmlspecialchars(),否则使用htmlentities()。

strip_tags() used when?

htmlspecialchars / entities encode the special chars, so they're displayed but not interpreted. strip_tags REMOVES them.

htmlspecialchars / entities对特殊字符进行编码,因此显示它们,但不解释它们。strip_tags删除它们。

In practice, it depends on what you need to do.

实际上,这取决于你需要做什么。

An example: you've coded a forum, and give users a text field so they can post stuff. Malicious ones just try:

例如:您编写了一个论坛,并为用户提供了一个文本字段,以便他们可以发布内容。恶意的试试:

pictures of <a href="javascript:void(window.setInterval(function () {window.open('http://evil.com');}, 1000));">kittens</a> here

If you don't do anything, the link will be displayed and a victim that clicks on the link gets lots of pop-ups.

如果你什么都不做,链接就会显示出来,点击链接的受害者会得到很多弹出窗口。

If you htmlentity/htmlspecialchar your output, the text will be there as-is. If you strip_tag it, it simply removes the tags and displays it:

如果您的输出是htmlentity/htmlspecialchar,那么文本将按原样存在。如果您对它进行strip_tag,它只需删除标记并显示它:

pictures of kittens here

Sometimes you may want a mixture, leave some tags in there, like <b> (strip_tags can leave certain tags in there). This is unsafe too, so better use some full blown library against XSS.

有时您可能需要混合,在其中保留一些标记,比如 (strip_tags可以在其中保留某些标记)。这也是不安全的,所以最好使用一些完整的库来对付XSS。

addslashes

To quote an old version of the PHP manual:

引用PHP手册的一个旧版本:

Returns a string with backslashes before characters that need to be quoted in database queries etc. These characters are single quote ('), double quote ("), backslash () and NUL (the NULL byte).

返回需要在数据库查询中引用的字符前有反斜杠的字符串。这些字符是单引号(')、双引号(")、反斜杠()和NUL(空字节)。

An example use of addslashes() is when you're entering data into a database. For example, to insert the name O'reilly into a database, you will need to escape it. It's highly recommeneded to use DBMS specific escape function (e.g. mysqli_real_escape_string() for MySQL or pg_escape_string() for PostgreSQL), but if the DBMS you're using does't have an escape function and the DBMS uses \ to escape special chars, you can use this function.

addslashes()的一个示例是当您将数据输入数据库时。例如,要将名称O'reilly插入数据库,您需要转义它。高度推荐使用DBMS特定的转义函数(例如,MySQL的mysqli_real_escape_string()或PostgreSQL的pg_escape_string())),但是如果您使用的DBMS没有转义函数,而且DBMS使用\来转义特殊的chars,您可以使用这个函数。

The current version is worded differently.

当前版本的措辞不同。

#2


5  

Only encode data at the point where it goes into the system it needs to be encoded for — otherwise you will run into situations where you want to manipulate the real data.

只在数据进入需要编码的系统时对其进行编码——否则您将遇到需要操作真实数据的情况。

For SQL injection - use bound variables as described in How can I prevent SQL injection in PHP? (it talks about prepared statements, but it is the binding that gives you protection, not the preparation).

对于SQL注入——使用绑定变量,如在PHP中如何防止SQL注入中所描述的那样?(它谈论的是事先准备好的陈述,但它是给你的保护,而不是准备)。

For XSS - if you are writing into HTML at point where either HTML or text is specified. Use htmlentities at the point where you generate your document. I would avoid storing the data in that form in the database (except possible in a write-rare-read-often system where CPU performance/disk access times were becoming and issue - then I would have a raw_ and an html_ version of the column … or just use memcached or similar).

对于XSS——如果您在指定HTML或文本的地方编写HTML。在生成文档的地方使用htmlentities。我将避免将数据以这种形式存储在数据库中(除了可能存在于CPU性能/磁盘访问时间变得异常频繁并发生问题的write-rare读系统中),然后我将拥有一个raw_和一个html_版本的列……或者仅仅使用memcached或类似的东西)。

If you are letting users enter URLs then you need to be more careful, as javascript:do_evil() is a valid URI that will execute (e.g. as an href for a clicked upon link or (in some browsers) the src of an image that is just loaded).

如果允许用户输入url,那么需要更加小心,因为javascript:do_evil()是一个有效的URI,它将执行(例如,作为单击的链接的href,或者(在某些浏览器中)刚刚加载的图像的src)。

#3


4  

I thought of this quick checklist:

我想到了这个简单的清单:

  • Always use HTTPS, without HTTPS your site is totally unencrypted. And no, client-side encrypting things and sending them won't work, think about it. Invalid HTTPS certificates also make you vulnerable to a MITM attack. Just use Let's Encrypt if you can't afford a certificate.
  • 总是使用HTTPS,没有HTTPS,你的网站完全没有加密。不,客户端加密和发送都不行,想想看。无效的HTTPS证书也使您容易受到MITM攻击。如果您负担不起证书,请使用Let's加密。
  • Always use htmlspecialchars() on any output from your PHP code, that is, or contains a user input. Most templating engines help you do that easily.
  • 总是在PHP代码的任何输出(即包含用户输入)上使用htmlspecialchars()。大多数模板引擎都可以帮助您轻松实现这一点。
  • Use HTTP-only flag in your php.ini to prevent scripts from accessing your cookies
  • 在php中使用仅http标志。ini防止脚本访问您的cookie
  • Prevent session-related problems
    • Never expose user's PHPSESSID (session ID) outside the cookie, if anybody gets to know a Session ID of somebody else, they can simply use it to login to their account
    • 不要将用户的PHPSESSID(会话ID)暴露在cookie之外,如果有人知道其他人的会话ID,他们可以使用它登录到自己的帐户
    • Be very careful with the Remember me function, show a little warning maybe.
    • 小心记住我的函数,可能会显示一些警告。
    • Refresh session ID when the user signs in (or whatever appropriate)
    • 当用户登录时刷新会话ID(或其他适当的方式)
    • Timeout inactive sessions
    • 超时不活跃的会议
  • 防止会话相关的问题永远不要将用户的PHPSESSID(会话ID)暴露在cookie之外,如果有人知道其他人的会话ID,他们可以简单地使用它登录到他们的帐户,使用Remember me函数要非常小心,可能会显示一些警告。当用户登录(或其他适当的)非激活会话超时时刷新会话ID
  • Never trust a cookie, it can be changed, removed, modified, and created by a script/user at any moment
  • 不要信任一个cookie,它可以随时被脚本/用户修改、删除、修改和创建
  • Prevent SQL-related problems
    • Always use prepared statements. Prepared statements causes the user input to be passed separately and prevents SQL Injection
    • 总是使用准备好的语句。准备语句导致用户输入被单独传递,并防止SQL注入
    • Make your code throw an exception when it fails. Sometimes your SQL server might be down for some reason, libraries like PDO ignore that error by default, and log a warning in the logs. This causes the variables you get from the DB to be null, depending on your code, this may cause a security issue.
    • 使您的代码在失败时抛出异常。有时,由于某些原因,您的SQL服务器可能会宕机,像PDO这样的库默认忽略这个错误,并在日志中记录一个警告。这将导致从DB获得的变量为null,这取决于您的代码,这可能导致安全问题。
    • Some libraries like PDO emulate prepared statements. Turn that off.
    • 有些库,如PDO,会模拟准备好的语句。关掉的。
    • Use UTF-8 encoding in your databases, it allows you to store virtually any character and avoid encoding-related attacks
    • 在数据库中使用UTF-8编码,可以存储几乎所有字符,避免与编码相关的攻击
    • Never concatenate anything to your query. Things like $myquery = "INSERT INTO mydb.mytable (title) VALUES(" . $user_input . ")" pretty much mean you have a huge security risk of an SQL injection.
    • 不要将任何内容连接到查询。$myquery = "插入到mydb中。(“mytable(标题)值。user_input美元。)“这几乎意味着SQL注入存在巨大的安全风险。”
  • 防止sql相关的问题总是使用准备好的语句。准备语句导致用户输入被单独传递,并防止SQL注入使代码在失败时抛出异常。有时,由于某些原因,您的SQL服务器可能会宕机,像PDO这样的库默认忽略这个错误,并在日志中记录一个警告。这将导致从数据库中获得的变量为null,这取决于您的代码,这可能会导致安全问题。有些库,如PDO,会模拟准备好的语句。将其关闭。在数据库中使用UTF-8编码,它允许您存储几乎任何字符,并且避免与编码相关的攻击,而不会将任何内容连接到您的查询。$myquery = "插入到mydb中。(“mytable(标题)值。user_input美元。)“这几乎意味着SQL注入存在巨大的安全风险。”
  • Store uploaded files in random, extension-less filenames. If a user uploads a file with .php file extension then whenever your code loads that file it executes it, and enables the user to execute some backend code
  • 以随机、无扩展的文件名存储上传的文件。如果用户上传了一个扩展名为.php的文件,那么无论何时您的代码加载它执行的文件,并且允许用户执行一些后端代码
  • Make sure you're not vulnerable to a CSRF attack.
  • 确保你不容易受到CSRF攻击。
  • Always update your PHP copy to ensure the latest security patches and performance improvements
  • 始终更新PHP副本,以确保最新的安全补丁和性能改进

#4


3  

You only need to use mysql_escape_string() when inserting into a database and htmlentites when displaying the HTML. This is sufficient if you want to prevent a simple injection attack, but there are no doubt many other security issues you should be aware of when developing a web app, another major one being cross site request forgeries.

当插入到数据库时,您只需要使用mysql_escape_string(),当显示HTML时则需要使用htmlentites。如果您想防止简单的注入攻击,那么这就足够了,但是毫无疑问,在开发web应用程序时,您应该意识到许多其他安全问题,另一个重要的问题是跨站点请求伪造。

#5


3  

htmlspecialchars() turns &, ', ", <, and > into an HTML entity format (&amp;, &quot;, etc.)

htmlspecialchars()将&、'、"、 <和> 转换为HTML实体格式(& '等)。

htmlentities() turns all applicable characters into their HTML entity format.

htmlentities()将所有适用的字符转换为其HTML实体格式。

strip_tags() removes all HTML and PHP tags.

strip_tags()删除所有HTML和PHP标记。

Both htmlspecialchars() and htmlentities() take an optional parameter indicating how quotation marks should be handled. See the PHP manual for specifics.

htmlspecialchars()和htmlentities()都接受一个可选参数,指示应该如何处理引号。有关详细信息,请参阅PHP手册。

The strip_tags() function takes an optional parameter indicating what tags should not be stripped.

函数的作用是:获取一个可选参数,指示哪些标签不应该被删除。

 $var = strip_tags ($var, '<p><br />');

The strip_tags() function will remove even invalid HTML tags, which may cause problems. For example, strip_tags() will yank out all of the code it thinks is an HTML tag, even if it’s improperly formed, like

strip_tags()函数甚至会删除无效的HTML标记,这可能会导致问题。例如,strip_tags()将删除它认为是HTML标记的所有代码,即使它的格式不正确。

<b I forgot to close the tag.

#6


2  

I wouldn't use htmlentities() when inserting data into the database or querying the database. If the data in you database is stored as entities, that data is then only useful to something that understands html entities.

在向数据库插入数据或查询数据库时,我不会使用htmlentities()。如果数据库中的数据存储为实体,那么该数据只对理解html实体的东西有用。

You have to use different escaping mechanisms for different types of output, e.g. SQL - mysql_real_escape_string(), HTML - htmlentities() or htmlspecialchars(), shell - escapeshellarg(). This is because the characters that are 'dangerous' are different for each one - there isn't a magic way you can make any data safe for any output medium.

您必须为不同类型的输出使用不同的转义机制,例如SQL - mysql_real_escape_string()、HTML - htmlentities()或htmlspecialchars()、shell - escapeshellarg()。这是因为“危险”字符对于每个字符都是不同的——没有一种神奇的方法可以使任何数据对任何输出介质都是安全的。

#7


1  

Take a look at this site PHP Security Consortium. I found it to be a good site for an overall overview on PHP Security (SQL Injection and XSS included).

看看这个网站PHP安全联盟。我发现它是一个很好的站点,可以对PHP安全性进行全面概述(包括SQL注入和XSS)。

#8


1  

I know it's an old question, but nowadays the most voted answer can be misleading for the beginners.

我知道这是一个老问题,但现在大多数投票的答案可能会误导初学者。

As of 2017

  1. You should never ever use mysql_real_escape_string. Even mysqli_real_escape_string is too weak to protect your database from the SQL injections. Instead of this, you should use PDO, and similar techniques. (see that guide)

    永远不要使用mysql_real_escape_string。甚至mysqli_real_escape_string也太弱了,无法保护数据库不受SQL注入的影响。相反,您应该使用PDO和类似的技术。(见指导)

  2. XSS (here I mean: strip_tags(), addslashes(), htmlspecialchars(), htmlentities()) - here the most voted answer is still correct, but I would suggest reading this article

    XSS(这里我的意思是:strip_tags()、addslashes()、htmlspecialchars()、htmlentities())——这里大多数投票的答案仍然是正确的,但是我建议阅读本文。