When to use htmlspecialchars vs filter_input ?
im confused when using htmlspecialchars vs filter_input for preventing bad input into php. I have got the hang of using prepared queries but I've not noticed when using the other two mentioned functions. Is htmlspecialchars mainly for outputting html to prevent XSS and is filter_input for handling the user input to prevent it from going through to cause harm?
8 Replies
The main reason I can think of is that
htmlspecialchars
exists in PHP for a long time and it has been retained for backwards compatibility, but that function has been generalized by the filter_input
function as of PHP 5.2.
While the htmlspecialchars
will convert characters specific to HTML, such as the <
and >
to their equivalent HTML entity (<
and >
), the filter_input
is configurable in regards to the type of filtering that it should perform.
It can be made to behave in the same manner as the old htmlspecialchars
by using the FILTER_SANITIZE_FULL_SPECIAL_CHARS
. But there are many other filters available.
For example, it's also typically used to validate email addresses:
Interesting
So do you use htmlspecialchars for getting post requests of info?
Yes,
htmlspecialchars
can also be used for that.
So, in response to your inquiry, filter_input
can also be used to prevent XSS attacks (provided you use an appropriate sanitization filter).
However, I recommend not escaping user input before saving it to the database. It's better to save the user input as is, and then only escape it when it's being rendered/echoed to a browser.Is this bad?
The script didn't run
that's how it's supposed to work
Then I used it correctly 🙂