Is FILTER_SANITIZE_STRING sufficient?

Currently I am using trim, stripslashes and htmlspecialchars to sanitise string data from forms. The data is being forwarded to clients in emails, not entered into a database.

I am considering changing to use just:
filter_var($str, FILTER_SANITIZE_STRING).

I quite like that FILTER_SANITIZE_STRING completely removes any HTML tags whereas with htmlspecialchars my clients would see some gobbledygook in received emails and would still see the code within HTML tags.

It’s puzzling as to why use of PHP filters to sanitise strings is not more frequently recommended. Is using FILTER_SANITIZE_STRING sufficient?

Depends on what you’re using the string for, really.

Thanks for your reply.

The string would just being forwarded in an email: for example a message from a ‘Contact Us’ website form.

Eh, for pasting to an email it’s probably sufficient, yeah. Just be careful with some of the other ones that dont strip tags… (people have a habit of using VALIDATE_EMAIL and not SANITIZE)

1 Like

It is actually recommended frequently for new development. The problem is, there was years of not having it and thus perpetuates through discussions because of it. If you are dealing with a posted form, you might consider just using filter_input with the INPUT_POST parameter. Save yourself some steps.

As for sufficient, as @m_hutley mentioned, really depends on what you are using it for. The email is probably ok but for other jobs it will depend on what you also pass in as options. The one problem with functions like this is that they are highly configurable. Great for flexibility, but sometimes can make things overly complicated by knowing which options to enable and disable.

:slight_smile:

Many thanks @Martyr2,

I think I will use FILTER_SANITIZE_STRING in future but also set the
FILTER_FLAG_NO_ENCODE_QUOTES flag as there seems to be no point having any single or double quotes encoded.

The only issue I am aware of is that if a string includes a single < character, it’s reported that the rest of the string is deleted by the filter (but I have not checked). I will have to accept that.