你可以在这个页面下载这个文档附带的文件,也可以在文件下载中的字符处理中下载这个文档描述如何安全显示的有格式的用户输入。我们将讨论没有经过过滤的输出的危险,给出一个安全的显示格式化输出的方法。
没有过滤输出的危险
如果你仅仅获得用户的输入然后显示它,你可能会破坏你的输出页面,如一些人能恶意地在他们提交的输入框中嵌入javascript脚本:
This is my comment.
<script language="javascript:
alert('Do something bad here!')">.
这样,即使用户不是恶意的,也会破坏你的一些HTML的语句,如一个表格突然中断,或是页面显示不完整。
只显示无格式的文本
这是一个最简单的解决方案,你只是将用户提交的信息显示为无格式的文本。使用htmlspecialchars()函数,将转化全部的字符为HTML的编码。
如<b>将转变为,这可以保证不会有意想不到的HTML标记在不适当的时候输出。
这是一个好的解决方案,如果你的用户只关注没有格式的文本内容。但是,如果你给出一些可以格式化的能力,它将更好一些。
Formatting with Custom Markup Tags
用户自己的标记作格式化
你可以提供特殊的标记给用户使用,例如,你可以允许使用[b]...[/b]加重显示,[i]...[/i]斜体显示,这样做简单的查找替换操作就可以了: $output = str_replace("[b]", "<b>", $output);
$output = str_replace("[i]", "<i>", $output);
再作的好一点,我们可以允许用户键入一些链接。例如,用户将允许输入[link="url"]...[/link],我们将转换为<a href="">...</a>语句
这时,我们不能使用一个简单的查找替换,应该使用正则表达式进行替换:
$output = ereg_replace('[link="([[:graph:]]+)"]', '<a href="\1">', $output);
ereg_replace()的执行就是:
查找出现[link="..."]的字符串,使用<a href="..."> 替换它
[[:graph:]]的含义是任何非空字符,有关正则表达式请看相关的文章。
在outputlib.php的format_output()函数提供这些标记的转换,总体上的原则是:
调用htmlspecialchars()将HTML标记转换成特殊编码,将不该显示的HTML标记过滤掉,然后,将一系列我们自定义的标记转换相应的HTML标记。
请参看下面的源代码:
<?php
function format_output($output) {
/****************************************************************************
* Takes a raw string ($output) and formats it for output using a special
* stripped down markup that is similar to HTML
****************************************************************************/
$output = htmlspecialchars(stripslashes($output));
/* new paragraph */
$output = str_replace('[p]', '<p>', $output);
/* bold */
$output = str_replace('[b]', '<b>', $output);
$output = str_replace('[/b]', '</b>', $output);
/* italics */
$output = str_replace('[i]', '<i>', $output);
$output = str_replace('[/i]', '</i>', $output);
/* preformatted */
$output = str_replace('[pre]', '<pre>', $output);
$output = str_replace('[/pre]', '</pre>', $output);
/* indented blocks (blockquote) */
$output = str_replace('[indent]', '<blockquote>', $output);
$output = str_replace('[/indent]', '</blockquote>', $output);
/* anchors */
$output = ereg_replace('[anchor="([[:graph:]]+)"]', '<a name="\1"></a>', $output);
/* links, note we try to prevent javascript in links */
$output = str_replace('[link="javascript', '[link=" javascript', $output);
$output = ereg_replace('[link="([[:graph:]]+)"]', '<a href="\1">', $output);
$output = str_replace('[/link]', '</a>', $output);
return nl2br($output);
}
?>
一些注意的地方:
记住替换自定义标记生成HTML标记字符串是在调用htmlspecialchars()函数之后,而不是在这个调用之前,否则你的艰苦的工作在调用htmlspecialchars()后将付之东流。
在经过转换之后,查找HTML代码将是替换过的,如双引号"将成为"
nl2br()函数将回车换行符转换为<br>标记,也要在htmlspecialchars()之后。
当转换[links=""] 到 <a href="">, 你必须确认提交者不会插入javascript脚本,一个简单的方法去更改[link="javascript 到 [link=" javascript, 这种方式将不替换,只是将原本的代码显示出来。
outputlib.php
在浏览器中调用test.php,可以看到format_output() 的使用情况
正常的HTML标记不能被使用,用下列的特殊标记替换它:
- this is [b]bold[/b]
- this is [i]italics[/i]
- this is [link="http://www.phpbuilder.com"]a link[/link]
- this is [anchor="test"]an anchor, and a [link="#test"]link[/link] to the anchor
[p]段落
[pre]预先格式化[/pre]
[indent]交错文本[/indent]
这些只是很少的标记,当然,你可以根据你的需求随意加入更多的标记
Conclusion
结论
这个讨论提供安全显示用户输入的方法,可以使用在下列程序中
留言板
用户建议
系统公告
BBS系统

PHP remains a powerful and widely used tool in modern programming, especially in the field of web development. 1) PHP is easy to use and seamlessly integrated with databases, and is the first choice for many developers. 2) It supports dynamic content generation and object-oriented programming, suitable for quickly creating and maintaining websites. 3) PHP's performance can be improved by caching and optimizing database queries, and its extensive community and rich ecosystem make it still important in today's technology stack.

In PHP, weak references are implemented through the WeakReference class and will not prevent the garbage collector from reclaiming objects. Weak references are suitable for scenarios such as caching systems and event listeners. It should be noted that it cannot guarantee the survival of objects and that garbage collection may be delayed.

The \_\_invoke method allows objects to be called like functions. 1. Define the \_\_invoke method so that the object can be called. 2. When using the $obj(...) syntax, PHP will execute the \_\_invoke method. 3. Suitable for scenarios such as logging and calculator, improving code flexibility and readability.

Fibers was introduced in PHP8.1, improving concurrent processing capabilities. 1) Fibers is a lightweight concurrency model similar to coroutines. 2) They allow developers to manually control the execution flow of tasks and are suitable for handling I/O-intensive tasks. 3) Using Fibers can write more efficient and responsive code.

The PHP community provides rich resources and support to help developers grow. 1) Resources include official documentation, tutorials, blogs and open source projects such as Laravel and Symfony. 2) Support can be obtained through StackOverflow, Reddit and Slack channels. 3) Development trends can be learned by following RFC. 4) Integration into the community can be achieved through active participation, contribution to code and learning sharing.

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP is not dying, but constantly adapting and evolving. 1) PHP has undergone multiple version iterations since 1994 to adapt to new technology trends. 2) It is currently widely used in e-commerce, content management systems and other fields. 3) PHP8 introduces JIT compiler and other functions to improve performance and modernization. 4) Use OPcache and follow PSR-12 standards to optimize performance and code quality.

The future of PHP will be achieved by adapting to new technology trends and introducing innovative features: 1) Adapting to cloud computing, containerization and microservice architectures, supporting Docker and Kubernetes; 2) introducing JIT compilers and enumeration types to improve performance and data processing efficiency; 3) Continuously optimize performance and promote best practices.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Chinese version
Chinese version, very easy to use

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function