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 Build a Basic PHP Website (2018) Enhancing a Form Escaping Output

When should you escape output?

Hi,

I understand what it does and how to use it, but don't understand when to use it?

  • Should it be used only on input elements?
  • Should it be used when echoing a variable? etc.

When is the best time to use it?

Thanks!

1 Answer

Caleb Kleveter
MOD
Caleb Kleveter
Treehouse Moderator 37,862 Points

When it comes to user defined data (anything that the user can create and send to your app/website), the answer is 'pretty much always'. We like to assume the best of people, but there are people out there that will try to do malicious hacking on your site.

For example, when you echo user input, whatever they sent in will be executed by the browser, so if they add malicious JavaScript the value you echo, that will be executed by browse. This is called an XXS attack.

A variable could easily be something you got from the database, and chances are that the data you fetched was sent by a user at some time. Unless only you can define a value that will be used, you should always escape data before echoing it, running it in a database query, or do just about anything else with it.

Hope that makes sense now!

Thanks Caleb. Please confirm my understanding. They should be used primarily for Forms or User Input fields, or anything being retrieved from a database?

I am assuming you wouldn't use it for a regular variable that is not related to a form or user input field?

Did I cover everything?

Caleb Kleveter
Caleb Kleveter
Treehouse Moderator 37,862 Points

That sounds right. I might have missed a couple of things myself, but that covers the basics.