FILTER_SANITIZE_STRING

FILTER_SANITIZE_STRING is deprecated

FILTER_SANITIZE_STRING was deprecated in PHP 8.1. It strips tags and may encode or remove some characters, but that does not make arbitrary input safe for every destination. For current PHP, validate according to the data you expect, store the intended value, and escape it for the output context.

$value = $_POST['name'] ?? '';
if (!is_string($value)) {
    $value = '';
}
$value = trim($value);

// Escape when placing the value into HTML text or attributes.
echo htmlspecialchars($value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');

Use dedicated validation when the value has a known format—for example FILTER_VALIDATE_EMAIL for an email address or ctype_alnum() when only letters and digits are acceptable.

Legacy behavior of FILTER_SANITIZE_STRING

Legacy reference: The following examples demonstrate what the deprecated filter used to do. Do not copy them as a current XSS-prevention pattern.
$str = "Welcome <script> alert(\"Hi plus2net\")</script>";
$str1 = filter_var($str, FILTER_SANITIZE_STRING);
echo $str1;

The legacy filter removed tags and transformed some characters. That transformation can change user data, and it is not a substitute for validating the expected value or escaping output for HTML, JavaScript, URLs, SQL, or another destination.

Legacy FILTER_FLAG_NO_ENCODE_QUOTES behavior

FILTER_FLAG_NO_ENCODE_QUOTES changed how quotes were handled by the deprecated filter. It did not turn the result into a universally safe value.

$str = "Welcome <script> alert(\"Hi plus2net\")</script>";
$str1 = filter_var(
    $str,
    FILTER_SANITIZE_STRING,
    FILTER_FLAG_NO_ENCODE_QUOTES
);

Related legacy flags

FILTER_FLAG_STRIP_LOW   // legacy flag for lower ASCII control characters
FILTER_FLAG_STRIP_HIGH  // legacy flag for bytes above ASCII 127
FILTER_FLAG_ENCODE_LOW  // legacy flag for encoding lower control characters
FILTER_FLAG_ENCODE_HIGH // legacy flag for encoding higher bytes
FILTER_FLAG_ENCODE_AMP  // legacy flag for encoding ampersands

Current pattern: validate, then escape for HTML

$name = $_POST['name'] ?? '';
if (!is_string($name)) {
    $name = '';
}
$name = trim($name);

if ($name === '' || mb_strlen($name) > 80) {
    echo 'Enter a name up to 80 characters.';
} else {
    echo htmlspecialchars($name, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}

This keeps validation and output encoding as separate steps. If the same value is later used in a database query, use a prepared statement rather than relying on string sanitization.


Filter reference Ctype_alnum to check alphanumeric characters Validating Email address


Subscribe to our YouTube Channel here



plus2net.com











PHP video Tutorials
✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer