Skip to content
PHP Logo

What are the best practices for validating HTML tags and attributes in user-generated content using PHP?

When dealing with user-generated content, it is important to validate HTML tags and attributes to prevent security vulnerabilities such as cross-site scripting (XSS) attacks. One way to achieve this is by using a library like HTML Purifier in PHP. HTML Purifier sanitizes the HTML input and only allows specified tags and attributes, ensuring that only safe and valid HTML is displayed on the website.

php
// Include HTML Purifier library
require_once 'path/to/HTMLPurifier.auto.php';

// Configuration for HTML Purifier
$config = HTMLPurifier_Config::createDefault();
$config->set('HTML.Allowed', 'p,b,a[href],i'); // Specify allowed tags and attributes

// Create HTML Purifier instance
$purifier = new HTMLPurifier($config);

// User-generated content
$userContent = '<p><script>alert("XSS attack!")</script></p>';

// Sanitize user content
$safeContent = $purifier->purify($userContent);

// Output sanitized content
echo $safeContent;