Hi I was wondering when is the appropriate place to use htmlspecialchars(). Is it before inserting data to database or when retrieving them from the database?
You should only call this method when echoing the data into HTML.
Don't store escaped HTML in your database; it will just make queries more annoying.
The database should store your actual data, not its HTML representation.
You use htmlspecialchars
EVERY time you output content within HTML, so it is interperted as content and not HTML.
If you allow content to be treated as HTML, you have just opened the door to bugs at a minimum, and total XSS hacks at worst.
Save the exact thing that the user enters into the database.
then when displaying it to public, use htmlspecialchars()
, so that it offers some xss protection.
Guide - How to use htmlspecialchars() function in PHP
To begin you have to understand 1 simple concept: Render.
What Render is? Render is when the HTML transforms
<b>Hello</b>
to bold like this Hello. That's render.
So...When to use the htmlspecialchars() function?
Wherever you want to render HTML contents. For example, if you are using JQuery and you do this:
$("#YourDiv").html("<b>Hello</b>");
The div contents will be Hello. It rendered the text into HTML.
If you want to display the message in this way (was wrote by user):
<b>Hello</b>
you have to put:
$("#YourDiv").text("<b>Hello</b>");
In that way the Hello will never be rendered.
If you want to load the message (as wrote by user) into a textbox, textarea, etc... You have to put:
<input type="text" class="Texbox1" value="">
<script>
$(".Textbox1").val("<b>Hello</b>");
</script>
That will display
<b>Hello</b>
Inside the Textbox without problems.
Conclusion:
What ever data the user input into your forms, etc...Save the data as normally. Do not use any function. If user sent 12345 save as it is. Do not filter nothing. You only have to filter when you are going to display the data in the page to the users. YOU, ONLY YOU decide if you want to render or not what the user wrote. *Remember that.
Regards!
© 2022 - 2024 — McMap. All rights reserved.