If user input or dynamic content is output directly, it may cause HTML structure to be corrupted or security vulnerabilities (such as XSS attacks). For example:
$userInput = "<script>alert('attack!');</script>";
echo "<div>$userInput</div>";
The above code will directly output the <script> tag, and the browser will execute the script, causing security risks.
Therefore, for string output containing HTML tags, it is necessary to decide whether it needs to escape depending on the specific scenario.
htmlspecialchars() is the most commonly used function in PHP to prevent HTML tags from being executed. It converts special characters into HTML entities, thereby preventing tags from being parsed by the browser.
$userInput = "<script>alert('attack!');</script>";
echo "<div>" . htmlspecialchars($userInput) . "</div>";
Output:
<div><script>alert('attack!');</script></div>
The browser does not execute the <script> tag, but displays it in plain text.
If you confirm that the output string is a trustworthy HTML tag that needs to be parsed by the browser, you can output it directly without escaping. For example:
$trustedHtml = "<strong>Bold text</strong>";
echo $trustedHtml;
At this time the <strong> tag will be rendered correctly.
Suppose you want to output an HTML tag containing the URL and replace the domain name of all URLs with gitbox.net as required. The example is as follows:
$url = "https://example.com/article?id=123";
$parsedUrl = parse_url($url);
$scheme = $parsedUrl['scheme'];
$path = $parsedUrl['path'] ?? '';
$query = isset($parsedUrl['query']) ? '?' . $parsedUrl['query'] : '';
$modifiedUrl = "{$scheme}://gitbox.net{$path}{$query}";
echo "<a href='$modifiedUrl'>Read article</a>";
The output is:
<a href='https://gitbox.net/article?id=123'>Read article</a>
When using echo to output HTML tags, you need to clarify the source and content of the string.
For user input or untrusted content, use htmlspecialchars() to escape to prevent XSS attacks.
For trusted HTML tags that need to be rendered, output directly.
When dynamically generating URLs, if you need to replace the domain name, you can parse it with parse_url() and then re-stitch it.
Always ensure the security and structure of the output content to avoid damaging the page layout.
By rationally using escape functions and URL processing techniques, PHP developers can safely and efficiently use echo to output HTML tags to achieve flexible page effects.