🔐
Security

Output encoding — complete protection from XSS attacks

15.06.2034
← All articles

Output encoding is a topic many developers do not give enough attention to but it is critically important for security. The main idea is simple: when you output data received from the user, you need to format it correctly for that context. In HTML — HTML encoding, in JavaScript — JavaScript encoding, in URL — URL encoding. Not knowing these differences leads to the biggest XSS vulnerabilities.

Encoding in HTML context

The most common case is outputting user-entered text to an HTML page. In PHP the htmlspecialchars() function is used for this. But it needs to be used correctly: htmlspecialchars($text, ENT_QUOTES | ENT_HTML5, 'UTF-8'). The ENT_QUOTES flag encodes both single and double quotes. ENT_HTML5 matches the modern HTML standard. If you only write htmlspecialchars($text), single quotes will not be encoded and there will be a vulnerability in the attribute context.

Encoding in JavaScript context

Sometimes you need to pass a value from PHP to JavaScript. Here htmlspecialchars() is not enough because in JavaScript context symbols \\ and \\n have different meaning. The correct way is to use json_encode(). json_encode automatically converts all dangerous symbols to safe format and returns a string wrapped in double quotes.

Encoding in URL context

When adding a parameter to URL you need to use urlencode() or rawurlencode(). This function converts special characters like & = ? # to safe format. If urlencode is not used the attacker can add "&admin=1" to a parameter and get admin rights.

Content Security Policy

CSP is a way to tell the browser "on this page only data from these sources can be loaded". Through the CSP header you can specify JavaScript only from your domain. Even if there is an XSS vulnerability, CSP prevents the attacker from loading external scripts.

Sayt.uz practice

On the Sayt.uz platform all user-entered data is filtered with htmlspecialchars() before output. json_encode is used in JSON responses. urlencode is applied in URL parameters. Content Security Policy headers are activated.

Related articles

🛡️ Ransomware Protection: Backups, Segmentation, EDR, and Incident Response 🎣 Protecting Employees from Phishing Attacks: Training and Technical Measures 📋 Security Audit Checklist: WordPress, Server, SSL, and Backup Review 🔐 SSL Certificate Monitoring: Expiry Tracking and Auto-Renewal
🌐 Language
🇺🇿 O'zbek 🇺🇿 Ўзбек 🇷🇺 Русский 🇬🇧 English