This document describes how to securely display formatted user input. We will discuss the danger of output without filtering, and provide a safe way to display and format the output.
No risk of filtering output
If you only obtain user input and display it, you may destroy your output page. For example, some people can maliciously embed it in the input box they submit.
Javascript script:
This is my comment.
<Script language = "javascript:
Alert ('Do something bad here! ') ">.
In this way, even if the user is not malicious, some HTML statements may be damaged, such as a table suddenly interrupted or the page display is incomplete.
Only show unformatted text
This is the simplest solution. You only display the information submitted by users as unformatted text. Use the htmlspecialchars () function to convert all characters into HTML encoding.
For example, <B> is changed to & lt; B & gt;, which ensures that no unexpected HTML Tag is output when it is not appropriate.
This is a good solution. If your users only pay attention to text content without format. However, if you provide some formatting capabilities, it will be better
Formatting with Custom Markup Tags
Format your own tags
You can provide special tags for users to use. For example, you can use...Aggravated display,...It is displayed in italic, so you can simply search for and replace it:
$ Output = str_replace (""," <B> ", $ output );
$ Output = str_replace (""," <I> ", $ output );
In addition, we can allow users to type some links. For example, you can enter [link = "url"]... [/link] and convert it to the <a href = "">... </a> statement.
In this case, we cannot use a simple search replacement. We should replace it with a regular expression:
$ Output = ereg_replace ('[link = "([: graph:] +)"]', '<a href = "1">', $ output );
The execution of ereg_replace () is:
Search for the string that appears [link = "..."] and replace it with <a href = "...">
[[: Graph:] indicates any non-null characters. For more information about regular expressions, see related articles.
The format_output () function in outputlib. php provides the conversion of these tags. The general principle is:
Call htmlspecialchars () to convert the HTML tag to a special encoding, and filter out the HTML Tag that should not be displayed,
Then, convert a series of custom tags into corresponding HTML tags.
<? Php
Function format_output ($ output ){
/*************************************** *************************************