简体   繁体   中英

When to use Strip_tags and when to use htmlspecialchars()

Every time I look at a code someone wrote, they either use

            $var = htmlspecialchars($var);
        $var = trim($var);
        $var = stripcslashes($var);

or just

strip_tags($var)

when to use the first and the second one?

htmlspecialchars and htmlentities are for displaying text in web pages. It will translate the characters that have special meaning in HTML, such as the < and > characters that surround tags, into their entity codes. For instance, if the string contains

Use <table> to create a table on a web page.

it will be converted to

Use &lt;table&gt; to create a table on a web page.

When you display the string on a web page, you'll then see the intended message correctly.

strip_tags completely removes all the HTML tags. So the above string would be converted to:

Use  to create a table on a web page.

If you display this, it doesn't make much sense. This is often used to sanitize input that isn't really meant for display, and shouldn't contain anything that looks like an HTML tag in the first place, such as usernames. Although it would probably be better to just validate it against whatever rules you have for those values (eg usernames should just be alphanumeric characters).

In my opinion, strip_tags() is almost always the wrong tool. It's a simple crutch to prevent XSS attacks, since code without any HTML tags can't introduce scripts. But it's a broad brush that doesn't usually match the specific needs.

And it's generally wrong to do these conversions when processing input. Do them when you're using the data, performing whatever escaping is necessary at that time. So you use mysqli_real_escape_string() if you're substituting the variable into a query (but you really should use prepared statements instead of this), htmlentities() when you're displaying it on a web page, urlencode() when you're putting it into a URL query string, etc.

In my case, i use htmlspecialchars() while passing url parameter in php. For eg

<?php
<a href="pages.php?id=<? echo htmlspecialchars($id); ?>"></a>
?>

This prevents cross site scripting, which means if users put some other code such as javascript, it replaces the reserved characters.

And i use strip_tags in forms, to prevent users from inserting tags into database.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM