← Back to Chapters

PHP htmlentities() & htmlspecialchars()

?️ PHP htmlentities() & htmlspecialchars()

? Quick Overview

PHP provides two useful functions, htmlentities() and htmlspecialchars(), that convert special characters into HTML entities. These functions are essential for preventing HTML injection and XSS attacks while ensuring text is displayed safely.

? Key Concepts

  • htmlentities() converts all applicable characters to HTML entities.
  • htmlspecialchars() converts only the most common special characters like <, >, and &.

? Syntax & Theory

  • htmlentities(string) encodes every special character.
  • htmlspecialchars(string) encodes only essential characters for HTML safety.

? Code Example: htmlentities()

? View Code Example
// Converts all special characters into HTML entities
<?php
$string = "This is a <b>bold</b> statement!";
$encoded = htmlentities($string);
echo $encoded;
?>

? Output Explanation

All HTML tags are converted into entity form, ensuring the browser displays them as plain text instead of executing them.

? Code Example: htmlspecialchars()

? View Code Example
// Escapes only critical HTML characters for safe rendering
<?php
$string = "This is a <b>bold</b> statement!";
$encoded = htmlspecialchars($string);
echo $encoded;
?>

? Output Explanation

Only critical characters are escaped, making this function ideal for safely displaying HTML code without breaking layout.

? Use Cases

  • Displaying user input safely on web pages
  • Preventing XSS attacks
  • Rendering HTML code examples

✅ Tips & Best Practices

  • Use htmlspecialchars() for most user input scenarios
  • Use htmlentities() for strict encoding needs
  • Always escape output, not input

? Try It Yourself

  • Compare outputs of both functions using different symbols
  • Test encoding with quotes and special characters
  • Use both functions with form input values