Best way to prevent XSS when rendering Markdown comments in PHP?
- Preparing a three-point takeaway…
Never pass raw user HTML into the DOM. Strip or escape angle brackets with htmlspecialchars($text, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') before expanding safe Markdown constructs, allowlist only https:// and http:// schemes on links (blocking javascript: and data: URIs), and add rel="ugc nofollow noopener" on untrusted outbound links. You can also validate XPath and DOM selectors safely during automated security checks.