What are the best practices for storing and retrieving user input with restricted HTML tags in a PHP application?

When storing user input with restricted HTML tags in a PHP application, it is important to sanitize the input to prevent any malicious code injection. One common approach is to use functions like htmlspecialchars() to encode the input before storing it in the database. When retrieving the input, use htmlspecialchars_decode() to decode the input and display it safely on the webpage.

// Sanitize user input before storing in the database
$restrictedInput = "<p>This is some <script>alert('malicious code')</script> input.</p>";
$cleanInput = htmlspecialchars($restrictedInput);

// Store $cleanInput in the database

// Retrieve and display the input safely on the webpage
$storedInput = "<p>This is some <script>alert('malicious code')</script> input.</p>";
$decodedInput = htmlspecialchars_decode($storedInput);
echo $decodedInput;