Current Location: Home> Latest Articles> Combining htmlspecialchars() to output HTML-safe data

Combining htmlspecialchars() to output HTML-safe data

M66 2025-05-28

We must be careful to avoid XSS (cross-site scripting attack) vulnerabilities when executing database queries and outputting data to HTML pages using PHP and MySQLi. This type of vulnerability usually occurs when directly outputting the content in the database to a web page without any escape or filtering.

To output content safely, htmlspecialchars() is a very useful tool. It converts HTML special characters (such as < , > , & , " etc.) into HTML entities, which prevents malicious scripts from being injected into the page. Combined with the mysqli_result object to get the database query results, we can safely display the content.

Here is a specific example showing how to use mysqli_result with htmlspecialchars() :

 <?php
// Database connection
$mysqli = new mysqli("localhost", "username", "password", "database");

// Check the connection
if ($mysqli->connect_errno) {
    die("Connection failed: " . $mysqli->connect_error);
}

// Execute a query
$sql = "SELECT id, title, content FROM articles";
$result = $mysqli->query($sql);

if ($result && $result->num_rows > 0) {
    echo "<h1>Article list</h1>";
    echo "<ul>";
    while ($row = $result->fetch_assoc()) {
        // Use htmlspecialchars Escape output
        $title = htmlspecialchars($row['title'], ENT_QUOTES, 'UTF-8');
        $content = htmlspecialchars($row['content'], ENT_QUOTES, 'UTF-8');

        // Suppose the article has a detailed link
        $articleUrl = "https://m66.net/article.php?id=" . urlencode($row['id']);

        echo "<li>";
        echo "<a href=\"$articleUrl\">$title</a><br>";
        echo "<p>$content</p>";
        echo "</li>";
    }
    echo "</ul>";
} else {
    echo "No article found。";
}

// Close the connection
$mysqli->close();
?>

Key points description

  1. Use htmlspecialchars()

    • The ENT_QUOTES parameter ensures that both single and double quotes are escaped.

    • 'UTF-8' specifies character encoding to avoid bypass problems caused by encoding.

  2. Use urlencode() when constructing URLs
    If you need to insert parameters in the URL, be sure to use urlencode() to prevent special characters from damaging the URL structure.

  3. Do not splice unprocessed data directly in HTML <br> Direct output of the values ​​of database fields is very dangerous and must be properly processed.

Summarize

In actual projects, developing the habit of escaping all data output to the browser is a basic requirement for security development. Combining the query results of mysqli_result and htmlspecialchars() , we can effectively prevent most XSS attacks and ensure the security of websites and users.

If you have parts that need further optimization, such as encapsulating output functions or using template engines, I can also organize them for you. Do you want me to write a more complete package example?