![]() Join Up! 96814 members and counting! |
|
|||
Displaying Formatted User Input
Ying Zhang
This document describes how to display safely formatted output from user
input. We will discuss the dangers of displaying unfiltered output
and then provide a safe means of displaying formatted output. Download
ying20000718.zip and extract it into
your web documents directory.
Dangers of Unfiltered Output
If you just took the user's input and displayed it as is, you may break
your webpage. For example, someone can maliciously embed javascript
in their comment like:
This is my comment.
<script language="javascript:
alert('Do something bad here!')">.Displaying Plain Text Only
The easiest solution would be to only display plain text in the comment.
Using the htmlspecialchars() function, you convert all the special
characters into HTML entites. For example <b> would become
<b>,
turning it into text instead of an HTML tag. This guarantees that
there are no HTML markups in the comment that would produce unwanted output.
This is an okay solution if your guests don't mind entering in only
plain text, but it would be a lot better if you gave them some formatting
abilities.
Formatting with Custom Markup Tags
You can provide your own special markup tags for the user to use.
For example, you can allow the to use [b]...[/b] for bolding, and
[i]...[/i]
for italics. Those would be simple string replace operations:
$output = str_replace("[b]", "<b>", $output);
$output = str_replace("[i]", "<i>", $output);
To get a little fancier, we will allow users to add links as well.
For example, the user will be allowed to enter in [link="url"]...[/link],
which we will turn into a proper <a href="">...</a> statement.
We can't use a simple string replace here, instead we need to use regular
expressions:$output = ereg_replace('\[link="([[:graph:]]+)"\]', '<a href="\\1">', $output);
The format_output() function in outputlib.php provides
these markups and a few other ones as well. The general algorithm
would be to:
<?phpSome notes:
outputlib.php
Load up the test.php script to see the format_output() in action.
function in action. Start by entering this in the textbox:
Regular HTML markup is not available, instead we will use special markup: - 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]This is a paragraph break [pre]This is preformatted text[/pre] [indent]This is indented text[/indent] This concludes our demonstration.
Currently there are only a small number of markups available - you are free to add
more as you see fit.
Conclusion
This article discussed the dangers of displaying unfiltered user input,
and provided a solution for displaying formatted user input with custom
markup tags. This can be applied anywhere you want to accept user input,
for example:
Enjoy!
--Ying
|