What are some best practices for allowing users to input custom code, like embedding code from external sources, in a PHP application?

When allowing users to input custom code, such as embedding code from external sources, it is important to sanitize and validate the input to prevent security vulnerabilities like code injection attacks. One common approach is to use functions like htmlspecialchars() to escape special characters and prevent cross-site scripting attacks. Additionally, you can restrict the types of code allowed by setting up a whitelist of allowed HTML tags, attributes, and protocols.

// Example of sanitizing user input in PHP
$user_input = "<script>alert('XSS attack!');</script>";
$sanitized_input = htmlspecialchars($user_input, ENT_QUOTES, 'UTF-8');
echo $sanitized_input;