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
Conta Excluída
Conta Excluída8mo ago
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 (&lt; and &gt;), 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:
$isValidEmail = filter_input(INPUT_POST, "email", FILTER_VALIDATE_EMAIL);

if ($isValidEmail) {
// ...
}
$isValidEmail = filter_input(INPUT_POST, "email", FILTER_VALIDATE_EMAIL);

if ($isValidEmail) {
// ...
}
MD
MD8mo ago
Interesting So do you use htmlspecialchars for getting post requests of info?
Conta Excluída
Conta Excluída8mo ago
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.
MD
MD8mo ago
Is this bad?
MD
MD8mo ago
No description
MD
MD8mo ago
The script didn't run
Jochem
Jochem8mo ago
that's how it's supposed to work
MD
MD8mo ago
Then I used it correctly 🙂
Want results from more Discord servers?
Add your server