'PHP - about filter sanitize string [duplicate]

A simple question, PHP 8.x from now not supporting FILTER_SANITIZE_STRING,

'FILTER_SANITIZE_STRING' is deprecated.

Should i replace it with:

htmlspecialchars() // Already by default charset UTF-8

What i need:

  • protect from XSS, where FILTER_SANITIZE_STRING removing <in between>.
  • It's ok if client signed up with <script>....(anyName)</script> and get his name only without telling him. (Already filtered with JS but if he ignored that).

Example:

<?php
$name = htmlspecialchars($_POST['userInput']);
$stmt = $pdo->prepare("INSERT INTO ......... VALUES (:zname)");
$stmt->execute([
   ":zname" => $name
]);

Will be safe to use this example instead of filter_var($_POST['userInput'], FILTER_SANITIZE_STRING); ?

Thank you.



Solution 1:[1]

htmlspecialchars is for HTML.

PDO needs to escape characters in a different way. Let $pdo->prepare(...) take care of things for you.

Note: That advice will leave UTF-8 characters in the database (which is appropriate) instead of things that look like &foobar; (which works turns into the foobar character in HTML, but is otherwise a string of ascii characters).

I think that gets rid of your clean function.

Meanwhile, all connections, all columns, etc, should be set to utf8mb4 (MySQL's term for UTF-8).

Solution 2:[2]

Installed opencart to see how they handle the request, this class is good:

class Request {
    public $get = array();
    public $post = array();
    public $cookie = array();
    public $files = array();
    public $server = array();
    public function __construct() {
        $this->get = $this->clean($_GET);
        $this->post = $this->clean($_POST);
        $this->request = $this->clean($_REQUEST);
        $this->cookie = $this->clean($_COOKIE);
        $this->files = $this->clean($_FILES);
        $this->server = $this->clean($_SERVER);
    }
    
    public function clean($data) {
        if (is_array($data)) {
            foreach ($data as $key => $value) {
                unset($data[$key]);

                $data[$this->clean($key)] = $this->clean($value);
            }
        } else {
            $data = htmlspecialchars($data, ENT_COMPAT, 'UTF-8');
        }

        return $data;
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Rick James
Solution 2 obeid_s