Apply for Zend Framework Certification Training

Corephp




< How to add date time in existing date and time in php How to convert seconds into days hours minutes and seconds >



Using htmlspecialchars() in PHP


Hi viewers,
While working with databases, we often receive data from users through HTML forms. Sometimes, the data entered by the user may contain special characters such as <, >, ", ', or &. If this data is displayed directly on a web page, it can create formatting problems or even security issues such as Cross-Site Scripting (XSS).


In PHP, we can use the htmlspecialchars() function to convert special HTML characters into safe HTML entities.
Important: htmlspecialchars() is mainly used when displaying data in HTML, not as the primary method for storing data in a database. For database security, use prepared statements.
Example
Suppose a user enters the following name:
$name = '<h1>Rajesh</h1>';
If we display it directly:
echo $name;
The browser will interpret <h1> as an HTML tag and display Rajesh as a heading.
Instead, use:
echo htmlspecialchars($name, ENT_QUOTES, 'UTF-8');
The browser will display:
<h1>Rajesh</h1>
rather than interpreting it as HTML.
Complete Example
<?php
$name = '<h1>Rajesh</h1>';
echo "Without htmlspecialchars():<br>";
echo $name;
echo "<br><br>";
echo "With htmlspecialchars():<br>";
echo htmlspecialchars($name, ENT_QUOTES, 'UTF-8');
?>
Output
Without htmlspecialchars():
Rajesh will appear as a large heading.
With htmlspecialchars():
<h1>Rajesh</h1>
The HTML tags are displayed as text.
Database Example
When storing user data in MySQL, use a prepared statement:
$name = $_POST['name'];
$stmt = $conn->prepare("INSERT INTO students (name) VALUES (?)");
$stmt->bind_param("s", $name);
$stmt->execute();
Then, when retrieving and displaying the name:
echo htmlspecialchars($name, ENT_QUOTES, 'UTF-8');
In Simple Words
Database storage: Use prepared statements.
HTML output: Use htmlspecialchars().
Password storage: Use password_hash().
Therefore, htmlspecialchars() helps us safely display user-entered data on a web page without allowing the browser to interpret the entered content as HTML or JavaScript.

< How to add date time in existing date and time in php How to convert seconds into days hours minutes and seconds >



Ask a question



  • Question:
    {{questionlistdata.blog_question_description}}
    • Answer:
      {{answer.blog_answer_description  }}
    Replay to Question


Back to Top