PHP中顯示格式化的用戶輸入
Jun 21, 2016 am 09:15 AM顯示
你可以在這個(gè)頁(yè)面下載這個(gè)文檔附帶的文件,也可以在文件下載中的字符處理中下載這個(gè)文檔描述如何安全顯示的有格式的用戶輸入。我們將討論沒(méi)有經(jīng)過(guò)過(guò)濾的輸出的危險(xiǎn),給出一個(gè)安全的顯示格式化輸出的方法。
沒(méi)有過(guò)濾輸出的危險(xiǎn)
如果你僅僅獲得用戶的輸入然后顯示它,你可能會(huì)破壞你的輸出頁(yè)面,如一些人能惡意地在他們提交的輸入框中嵌入javascript腳本:
This is my comment.
<script language="javascript:
alert('Do something bad here!')">.
這樣,即使用戶不是惡意的,也會(huì)破壞你的一些HTML的語(yǔ)句,如一個(gè)表格突然中斷,或是頁(yè)面顯示不完整。
只顯示無(wú)格式的文本
這是一個(gè)最簡(jiǎn)單的解決方案,你只是將用戶提交的信息顯示為無(wú)格式的文本。使用htmlspecialchars()函數(shù),將轉(zhuǎn)化全部的字符為HTML的編碼。
如<b>將轉(zhuǎn)變?yōu)?b>,這可以保證不會(huì)有意想不到的HTML標(biāo)記在不適當(dāng)?shù)臅r(shí)候輸出。
這是一個(gè)好的解決方案,如果你的用戶只關(guān)注沒(méi)有格式的文本內(nèi)容。但是,如果你給出一些可以格式化的能力,它將更好一些。
Formatting with Custom Markup Tags
用戶自己的標(biāo)記作格式化
你可以提供特殊的標(biāo)記給用戶使用,例如,你可以允許使用...加重顯示,...斜體顯示,這樣做簡(jiǎn)單的查找替換操作就可以了: $output = str_replace("", "<b>", $output);
$output = str_replace("", "<i>", $output);
再作的好一點(diǎn),我們可以允許用戶鍵入一些鏈接。例如,用戶將允許輸入[link="url"]...[/link],我們將轉(zhuǎn)換為<a href="">...</a>語(yǔ)句
這時(shí),我們不能使用一個(gè)簡(jiǎn)單的查找替換,應(yīng)該使用正則表達(dá)式進(jìn)行替換:
$output = ereg_replace('\[link="([[:graph:]]+)"\]', '<a href="\\1">', $output);
ereg_replace()的執(zhí)行就是:
查找出現(xiàn)[link="..."]的字符串,使用<a href="..."> 替換它
[[:graph:]]的含義是任何非空字符,有關(guān)正則表達(dá)式請(qǐng)看相關(guān)的文章。
在outputlib.php的format_output()函數(shù)提供這些標(biāo)記的轉(zhuǎn)換,總體上的原則是:
調(diào)用htmlspecialchars()將HTML標(biāo)記轉(zhuǎn)換成特殊編碼,將不該顯示的HTML標(biāo)記過(guò)濾掉,
然后,將一系列我們自定義的標(biāo)記轉(zhuǎn)換相應(yīng)的HTML標(biāo)記。
請(qǐng)參看下面的源代碼:
<?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>', $output);
/* italics */
$output = str_replace('[i]', '<i>', $output);
$output = str_replace('', '</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);
}
?>
一些注意的地方:
記住替換自定義標(biāo)記生成HTML標(biāo)記字符串是在調(diào)用htmlspecialchars()函數(shù)之后,而不是在這個(gè)調(diào)用之前,否則你的艱苦的工作在調(diào)用htmlspecialchars()后將付之東流。
在經(jīng)過(guò)轉(zhuǎn)換之后,查找HTML代碼將是替換過(guò)的,如雙引號(hào)"將成為"
nl2br()函數(shù)將回車換行符轉(zhuǎn)換為<br>標(biāo)記,也要在htmlspecialchars()之后。
當(dāng)轉(zhuǎn)換[links=""] 到 <a href="">, 你必須確認(rèn)提交者不會(huì)插入javascript腳本,一個(gè)簡(jiǎn)單的方法去更改[link="javascript 到 [link=" javascript, 這種方式將不替換,只是將原本的代碼顯示出來(lái)。
outputlib.php
在瀏覽器中調(diào)用test.php,可以看到format_output() 的使用情況
正常的HTML標(biāo)記不能被使用,用下列的特殊標(biāo)記替換它:
- this is bold
- this is italics
- 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]預(yù)先格式化[/pre]
[indent]交錯(cuò)文本[/indent]
這些只是很少的標(biāo)記,當(dāng)然,你可以根據(jù)你的需求隨意加入更多的標(biāo)記
Conclusion
結(jié)論
這個(gè)討論提供安全顯示用戶輸入的方法,可以使用在下列程序中
留言板
用戶建議
系統(tǒng)公告
BBS系統(tǒng)

Hot AI Tools

Undress AI Tool
Undress images for free

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

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

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

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

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service
