<p&amp;gt;For HTML output, apply context-aware escaping: use HTML entity encoding for text and attributes, and combine with JavaScript escaping in scripts; 2. For JSON, always use built-in serializers and escape special characters like </p&amp;gt;
<p&amp;gt;<img src="/static/imghw/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/175364898234231.jpg" class="lazy" alt="Context is King: Tailoring Escape Strategies for HTML, JSON, and SQL Output"&amp;gt;</p&amp;gt;
<p&amp;gt;When building web applications, generating dynamic output is unavoidable — whether it’s rendering user data in HTML, serving APIs with JSON, or storing information in SQL databases. But here’s the catch: <strong&amp;gt;the same data can be dangerous in different contexts</strong&amp;gt;. A string that’s perfectly safe in JSON might be a ticking time bomb in HTML. That’s why one-size-fits-all escaping doesn’t work. <strong&amp;gt;Context is king</strong&amp;gt; — and your escape strategy must adapt accordingly.</p&amp;gt;
<img src="/static/imghw/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/175364898389353.jpeg" class="lazy" alt="Context is King: Tailoring Escape Strategies for HTML, JSON, and SQL Output"&amp;gt;<p&amp;gt;Let’s break down how and why escaping differs across HTML, JSON, and SQL — and what you should actually do to stay safe in each.</p&amp;gt;
<hr&amp;gt;
<h3 id="HTML-Output-Beware-of-Injection-Points"&amp;gt;1. HTML Output: Beware of Injection Points</h3&amp;gt;
<p&amp;gt;When user-generated content is inserted into HTML, the main threat is <strong&amp;gt;Cross-Site Scripting (XSS)</strong&amp;gt;. The danger lies in how and where the data is placed.</p&amp;gt;
<img src="/static/imghw/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/175364898481960.jpeg" class="lazy" alt="Context is King: Tailoring Escape Strategies for HTML, JSON, and SQL Output"&amp;gt;<h4 id="Key-Rule-Escape-based-on-context-within-HTML"&amp;gt;Key Rule: Escape based on context within HTML</h4&amp;gt;
<ul&amp;gt;
<li&amp;gt;
<strong&amp;gt;In text content</strong&amp;gt;: Use HTML entity encoding (<code&amp;gt; → &amp;lt;code&amp;gt;, &amp;lt;code&amp;gt;&amp;gt;</code&amp;gt; → <code&amp;gt;&amp;gt;</code&amp;gt;, <code&amp;gt;&amp;</code&amp;gt; → <code&amp;gt;&amp;</code&amp;gt;, etc.)</code&amp;gt;</code&amp;gt;
</li&amp;gt;
<li&amp;gt;
<strong&amp;gt;In attributes</strong&amp;gt;: Still use entity encoding, but also ensure quotes are escaped (<code&amp;gt;"</code&amp;gt; → <code&amp;gt;"</code&amp;gt;) if inside double quotes</li&amp;gt;
<li&amp;gt;
<strong&amp;gt;In JavaScript blocks or event handlers</strong&amp;gt;: This is a <em&amp;gt;nested context</em&amp;gt; — you need both HTML and JavaScript escaping</li&amp;gt;
<li&amp;gt;
<strong&amp;gt;In URLs (e.g., href, src)</strong&amp;gt;: Validate and sanitize protocols (block <code&amp;gt;javascript:</code&amp;gt;), and URL-encode where necessary</li&amp;gt;
</ul&amp;gt;
<h4 id="Example"&amp;gt;Example:</h4&amp;gt;<pre class='brush:php;toolbar:false;'&amp;gt;&amp;lt;!-- Unsafe --&amp;gt;
&amp;lt;div&amp;gt;Hello &amp;lt;script&amp;gt;alert('xss')&amp;lt;/script&amp;gt;&amp;lt;/div&amp;gt;
&amp;lt;!-- Safe after HTML escaping --&amp;gt;
&amp;lt;div&amp;gt;Hello &amp;lt;script&amp;gt;alert('xss')&amp;lt;/script&amp;gt;&amp;lt;/div&amp;gt;</pre&amp;gt;<p&amp;gt;? <strong&amp;gt;Pro tip</strong&amp;gt;: Use templating engines (like Django templates, React, or Handlebars) that auto-escape by default — but verify they’re context-aware. Never use <code&amp;gt;innerHTML</code&amp;gt; with raw user input.</p&amp;gt;<hr /&amp;gt;<h3 id="JSON-Output-Watch-for-Script-Breakouts"&amp;gt;2. JSON Output: Watch for Script Breakouts</h3&amp;gt;<p&amp;gt;JSON is often seen as “safe” because it’s just data — but when embedded in HTML or served in responses parsed by JavaScript, it can still lead to XSS.</p&amp;gt;<img src="/static/imghw/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/175364898550303.jpeg" class="lazy" alt="Context is King: Tailoring Escape Strategies for HTML, JSON, and SQL Output" /&amp;gt;<h4 id="Key-Rule-Escape-control-characters-and-HTML-sensitive-chars"&amp;gt;Key Rule: Escape control characters and HTML-sensitive chars</h4&amp;gt;<ul&amp;gt;<li&amp;gt;Encode <code&amp;gt;<</code&amp;gt;, <code&amp;gt;&amp;gt;</code&amp;gt;, and <code&amp;gt;&amp;</code&amp;gt; as <code&amp;gt;\u003c</code&amp;gt;, <code&amp;gt;\u003e</code&amp;gt;, <code&amp;gt;\u0026</code&amp;gt; when JSON is embedded in HTML (e.g., in a script tag)</li&amp;gt;<li&amp;gt;Always set correct <code&amp;gt;Content-Type: application/json</code&amp;gt; to prevent MIME-type sniffing</li&amp;gt;<li&amp;gt;Escape U 2028 (line separator) and U 2029 (paragraph separator) — these can break JavaScript parsers</li&amp;gt;</ul&amp;gt;<h4 id="Example"&amp;gt;Example:</h4&amp;gt;<pre class='brush:php;toolbar:false;'&amp;gt;// Dangerous if not escaped
&amp;lt;script&amp;gt;
var userData = {&amp;quot;name&amp;quot;: &amp;quot;&amp;lt;script&amp;gt;alert(1)&amp;lt;/script&amp;gt;&amp;quot;};
&amp;lt;/script&amp;gt;
// Safe with proper escaping
var userData = {&amp;quot;name&amp;quot;: &amp;quot;\u003cscript\u003ealert(1)\u003c/script\u003e&amp;quot;};</pre&amp;gt;<p&amp;gt;? Use built-in JSON serializers (<code&amp;gt;JSON.stringify()</code&amp;gt; in JS, <code&amp;gt;json_encode()</code&amp;gt; in PHP, etc.) — they handle most of this correctly <em&amp;gt;if used properly</em&amp;gt;. But never concatenate JSON from strings — always serialize structured data.</p&amp;gt;<hr /&amp;gt;<h3 id="SQL-Queries-Never-Trust-Strings"&amp;gt;3. SQL Queries: Never Trust Strings</h3&amp;gt;<p&amp;gt;SQL injection remains a top vulnerability. The issue? User input gets interpreted as executable code.</p&amp;gt;<h4 id="Key-Rule-Use-parameterized-queries-not-escaping"&amp;gt;Key Rule: Use parameterized queries — not escaping</h4&amp;gt;<ul&amp;gt;<li&amp;gt;Forget manual escaping (like <code&amp;gt;mysql_real_escape_string</code&amp;gt;) — it’s error-prone and outdated</li&amp;gt;<li&amp;gt;Use <strong&amp;gt;prepared statements</strong&amp;gt; with <strong&amp;gt;parameterized queries</strong&amp;gt;</li&amp;gt;<li&amp;gt;Parameters are sent separately from the query structure, so they’re never parsed as SQL</li&amp;gt;</ul&amp;gt;<h4 id="Example-Python-with-psycopg"&amp;gt;Example (Python with psycopg2):</h4&amp;gt;<pre class='brush:php;toolbar:false;'&amp;gt;# ? Dangerous
query = f&amp;quot;SELECT * FROM users WHERE name = '{name}'&amp;quot;
cursor.execute(query)
# ? Safe
cursor.execute(&amp;quot;SELECT * FROM users WHERE name = %s&amp;quot;, (name,))</pre&amp;gt;<p&amp;gt;?? ORM libraries (like SQLAlchemy, Django ORM, or Entity Framework) also help by defaulting to safe patterns — but watch out for raw SQL sections.</p&amp;gt;
<hr&amp;gt;
<h3 id="Summary-Match-the-Escape-to-the-Context"&amp;gt;Summary: Match the Escape to the Context</h3&amp;gt;
<table&amp;gt;
<thead&amp;gt;<tr&amp;gt;
<th&amp;gt;Context</th&amp;gt;
<th&amp;gt;Primary Threat</th&amp;gt;
<th&amp;gt;Safe Strategy</th&amp;gt;
</tr&amp;gt;</thead&amp;gt;
<tbody&amp;gt;
<tr&amp;gt;
<td&amp;gt;HTML</td&amp;gt;
<td&amp;gt;XSS</td&amp;gt;
<td&amp;gt;Context-aware HTML escaping; use auto-escaping templates</td&amp;gt;
</tr&amp;gt;
<tr&amp;gt;
<td&amp;gt;JSON</td&amp;gt;
<td&amp;gt;Script injection in HTML/JS</td&amp;gt;
<td&amp;gt;
<code&amp;gt;\u</code&amp;gt; escaping for special chars; always use JSON serializer</td&amp;gt;
</tr&amp;gt;
<tr&amp;gt;
<td&amp;gt;SQL</td&amp;gt;
<td&amp;gt;SQL injection</td&amp;gt;
<td&amp;gt;Parameterized queries — never string concatenation</td&amp;gt;
</tr&amp;gt;
</tbody&amp;gt;
</table&amp;gt;
<p&amp;gt;You can’t just “escape everything” with one function and call it a day. The same user input — say, <code&amp;gt;O'Reilly <script&amp;gt;test</script&amp;gt;</code&amp;gt; — needs:</p&amp;gt;
<ul&amp;gt;
<li&amp;gt;Apostrophe handled in SQL (via parameters)</li&amp;gt;
<li&amp;gt;Tags escaped in HTML</li&amp;gt;
<li&amp;gt;Possibly escaped in JSON if embedded in a page</li&amp;gt;
</ul&amp;gt;
<p&amp;gt;<strong&amp;gt;Bottom line</strong&amp;gt;: Always ask: <em&amp;gt;Where is this going?</em&amp;gt; The output context dictates the defense. Get that right, and you’re already ahead of most breaches.</p&amp;gt;
<p&amp;gt;Basically, it’s not about escaping — it’s about <strong&amp;gt;understanding the language of the destination</strong&amp;gt;.</p&amp;gt;
The above is the detailed content of Context is King: Tailoring Escape Strategies for HTML, JSON, and SQL Output. For more information, please follow other related articles on the PHP Chinese website!