4.7.14 Removing HTML from a string: strip_tags()This is NOT the latest copy of this book; click here for the latest version.
string strip_tags ( string source [, string allowable_tags])
Strip_tags() is a function that allows you to strip out all HTML and PHP tags from a given string (parameter one), however you can also use parameter two to specify a list of HTML tags you want.
This function can be very helpful if you ever display user input on your site. For example, if you create your own messageboard forum on your site a user could post a title along the lines of: <H1>THIS SITE SUCKS!</H1>, which, because you would display the titles of each post on your board, would display their unwanted message in huge letters on your visitors' screens.
Here are two examples of stripping out tags:
<?php
$input = "<BLINK><B>Hello!</B></BLINK>";
$a = strip_tags($input);
$b = strip_tags($input, "<B><I>"); ?>
After running that script, $a will be set to "Hello!", whereas $b will be set to "<B>Hello!</B>" because we had "<B>" in the list of acceptable tags. Using this method you can eliminate most users from adversely changing the style of your site, however it is still possible for users to cause trouble if you allow a list of certain HTML tags, for example, we could abuse the allow <B> tag using CSS: <B STYLE="font: 72pt Times New Roman">THIS SITE SUCKS!</B>.

If you allow <B> tags, you allow all <B> tags, regardless of whether they have any extra unwanted information in there, so it is best not to allow any tags.
This sort of attack is commonly referred to as Cross-Site Scripting (XSS), as it allows people to take advantage of user input on your site to load their own content that may make your site look bad. Even worse than that is the fact that it's fairly easy for malicious users to make their username (for example) a JavaScript document that redirects the user to their own site and passes along all their cookies from your site, which can have disastrous effects. Be careful - make sure and put strip_tags() to good use.
|
Want to see this stuff in print? PHP in a Nutshell takes the core topics covered here, adds in thousands of edits from the editorial team and myself, and combines them to make an unbeatable reference for PHP programmers at all levels.
My latest book has hundreds more tips on how to use PHP, Apache, and MySQL, plus Perl, Python, shell scripts, performance tuning, and more!
|