FILTER_SANITIZE_STRING is deprecated, what to use instead?

As PHP 8.1.0 FILTER_SANITIZE_STRING is deprecated. Let’s see what function should you use instead.

What is FILTER_SANITIZE_STRING?

This sanitization filter allows you to strip tags and HTML-encode double and single quotes. You can also strip or encode special characters.ย 

If you are using this on PHP 8.1.0 or above you will get a deprecated warning.

Deprecated warning of FILTER_SANITIZE_STRING in VS code with intelephense extension

htmlspecialchars

The official PHP documentation recommends htmlspecialchars instead of FILTER_SANITIZE_STRING

Let’s take a look at some examples

$string_1 = htmlspecialchars("<h2>some heading</h2>", ENT_QUOTES); 
// &lt;h2&gt;some heading&lt;/h2&gt;

$string_2 = html_entity_decode($string_1); // <h2>some heading</h2>
$string_3 = "<h2>some heading</h2>";

filter_var ( $string_3, FILTER_SANITIZE_STRING); // <h2>some heading</h2>

So if you want to sanitize a string and remove or encode HTML characters use htmlspecialchars

Further reading:
PHP official docs

https://www.php.net/manual/en/function.htmlspecialchars.php


Leave a Reply

Your email address will not be published. Required fields are marked *