0
0
PHPprogramming~5 mins

Output escaping with htmlspecialchars in PHP

Choose your learning style9 modes available
Introduction

We use htmlspecialchars to safely show text on a web page. It stops special characters from breaking the page or causing security problems.

When showing user comments on a blog to avoid breaking the page layout.
When displaying form input back to the user to prevent code running in the browser.
When printing any text that might contain special HTML characters like <, >, &, or quotes.
When you want to protect your website from hackers trying to insert harmful code.
When you want to make sure the text looks exactly as typed, not as HTML.
Syntax
PHP
htmlspecialchars(string $string, int $flags = ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401, string $encoding = 'UTF-8', bool $double_encode = true): string

The first argument is the text you want to escape.

The function changes special characters like <, >, &, ' and " into safe codes.

Examples
This changes <b> and & into safe codes so the browser shows them as text, not as HTML tags.
PHP
$safe = htmlspecialchars("<b>Hello & Welcome</b>");
echo $safe;
This also converts single quotes to safe codes, so they show correctly.
PHP
$text = "Tom's book";
echo htmlspecialchars($text, ENT_QUOTES);
Special math symbols like > and < are converted so they display as text.
PHP
$text = "5 > 3 & 2 < 4";
echo htmlspecialchars($text);
Sample Program

This program takes a string that looks like code and changes it so the browser shows it as text, not as a script.

PHP
<?php
$user_input = "<script>alert('Hi');</script>";
$safe_output = htmlspecialchars($user_input);
echo "User input safely shown: " . $safe_output . "\n";
?>
OutputSuccess
Important Notes

Always use htmlspecialchars when showing user input in HTML to avoid security risks.

Remember to set the correct character encoding (usually UTF-8) to avoid problems with special characters.

Using ENT_QUOTES flag converts both single and double quotes, making output safer.

Summary

htmlspecialchars changes special HTML characters into safe codes.

It helps protect your website from unwanted code running in the browser.

Use it whenever you show text that might contain HTML special characters.