mysql_real_escape_string used when insert into database
htmlentities() used when outputting data into webpage
htmlspecialchars() used when??
strip_tags() used when ??
addslashes() used when ??
htmlspecialchars() used when??
htmlspecialchars is roughly the same as htmlentities. the difference: character encodings.
both encode control characters like <
, >
, &
and so on used for opening tags etc. htmlentities also encode chars from other languages like umlauts, euro-symbols and such. if your websites are utf, use htmlspecialchars(), otherwise use htmlentities().
strip_tags() used when ??
htmlspecialchars / entities encode the special chars, so they're displayed but not interpreted. strip_tags REMOVES them.
in practice, it depends on what you need to do.
an example ... you've coded a forum, and give users a text field so they can post stuff. malicious ones just try
pictures of <a href="javascript:void(window.setInterval(function () {window.open('http://evil.com');}, 1000));">kittens</a> here
if you don't do anything, the link will be display'd and a victim that clicks on the link gets lots of pop-ups.
if you htmlentitiy/htmlspecialchar your output, the text will be there as-is. if you strip_tag it, it simply removes the tags and displays it:
pictures of kittens here
sometimes you may want a mixture, leave some tags in there, like <b>
(strip_tags can leave certain tags in there). this is unsafe too, so better use some full blown library against xss
addslashes
to quote the php manual:
Returns a string with backslashes before characters that need to be quoted in database queries etc. These characters are single quote ('), double quote ("), backslash () and NUL (the NULL byte).
An example use of addslashes() is when you're entering data into a database. For example, to insert the name O'reilly into a database, you will need to escape it. It's highly recommeneded to use DBMS specific escape function (e.g. mysqli_real_escape_string() for MySQL or pg_escape_string() for PostgreSQL), but if the DBMS you're using does't have an escape function and the DBMS uses \ to escape special chars, you can use this function.