I am abot confusing, there are so many functions in PHP, and some using this, some using that. Some people use:
$var = mysql_real_escape_string(htmlentities($_POST['username']));
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 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().
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
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
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.