Home Backend Development PHP Tutorial Display formatted user input in PHP_PHP Tutorial

Display formatted user input in PHP_PHP Tutorial

Jul 13, 2016 pm 05:36 PM
php Danger exist Safety show format user of discuss enter output filter

我们将讨论没有经过过滤的输出的危险,给出一个安全的显示格式化输出的方法。

  没有过滤输出的危险


  如果你仅仅获得用户的输入然后显示它,你可能会破坏你的输出页面,如一些人能恶意地在他们提交的输入框中嵌入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()函数提供这些标记的转换,总体上的原则是:中国网管联盟bitsCN.com

  调用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);网管bitscn_com
/* 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()后将付之东流。网管bitscn_com

  在经过转换之后,查找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]Paragraph
[pre]Pre-formatted[/pre]
[indent]Interleaved text[/indent]

These are just a few tags, of course, you can add more tags according to your needs. Network Management Alliance bitsCN@com

Conclusion

Conclusion

This discussion provides methods for safely displaying user input, which can be used in the following programs

Message Board
User Suggestions
System Announcement
BBS System

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/508214.htmlTechArticleWe will discuss the dangers of unfiltered output and give a safe way to display formatted output. No danger of filtering output If you just get input from the user and display...
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles