Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is difference between php strip_tags and filter_var function?

Tags:

php

They both seems to stripe out html,javascript tags. So when to use which? I have tried both like

<?php

$user_input = "<script>alert('Your site sucks!');</script>";

echo strip_tags($user_input);

?>

And

<?php

$user_input = "<script>alert('Your site sucks!');</script>";

echo filter_var($user_input, FILTER_SANITIZE_STRIPPED);

?>
like image 746
Akash Salunkhe Avatar asked Feb 06 '18 09:02

Akash Salunkhe


2 Answers

strip_tags strictly filters all html and php tags from a given string.

filter_var filters out based on multiple different flags that you can provide. It does not rectify a string, but it validates it instead

IE: if you use filter_var with flag: FILTER_VALIDATE_EMAIL, if you give it a valid email address, it will return it as it is, while an invalid email will return false

like image 134
Ralph Melhem Avatar answered Nov 15 '22 13:11

Ralph Melhem


strip_tags() does just that. According to PHP documentation it:

strips HTML and PHP tags from a string

filter_var() gives you a bit more to work with as you can use different filters with it i.e. FILTER_SANITIZE_EMAIL will sanitize the string to return a valid email.

In terms difference between strip_tags and filter_var with FILTER_SANITIZE_STRIPPED specifically strip_tags will allow less than symbol and filter_var with FILTER_SANITIZE_STRIPPED will remove it.

I.e.:

strip_tags("testing < practice") will return "testing < practice"
filter_var("testing < practice", FILTER_SANITIZE_STRIPPED) will return "testing "
like image 38
Kasia Gogolek Avatar answered Nov 15 '22 13:11

Kasia Gogolek