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?


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

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! 🙌