Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP Working with $_GET and $_POST in PHP Filtering Inputs and Escaping Outputs Always Escape Outputs

htmlenteties/chars in Database

What is unclear to me still is a best practice regarding using hmtlspecialchars/entities for storing data in database. Is it better to store encoded data in database or decoded as a string?

Example:

If I receive this data in the form of JSON should I html_entity_decode before storing in database or leave as is? { question: "Which of the following is the world's best-selling book?" }

If I leave as is will it display properly in html or will it need to be decoded and then re encoded before being sent to a web browser for display?

1 Answer

jonathanbarrios
STAFF
jonathanbarrios
Treehouse Teacher

The best practice is...

Always filter inputs: The filter_input() function filters and validates external variables and used to prevent security threats like SQL Injection(SQLi) attacks.

Always Escape Outputs: Encode special characters in order to make sure you don't accidentally add malicious or broken HTML to a page. For example, say you wrote a script that reads a piece of data from a database, and output that data to a web page. If the data retrieved from the database(even JSON) was something like this -- <script>alert('You've been hacked');</script> -- then sending this to a web browser as-is could execute this JavaScript code.

Always filter inputs and escape outputs. Happy coding! πŸ™Œ