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

Wouldn't it be safer to use the escape characters function when the user clicks the send button?

Or use the htmlspecialchars function on the output of the trim function when we initially extract the variables from $_POST?

2 Answers

Robert Walker
Robert Walker
17,146 Points

I would personally check it on submit.

I would also use JavaScript as an added check, this way you can filter out before it gets submitted.

You will however run into problems if people have JavaScript turned off so its always best to check them on submit too.

function test_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}

$loginUsername = test_input($_POST['username']);

Just run all submitted data through that function before using them in anything that submits to a database etc.

You should only validate the user input at the point it is needed for example right before sending it to database or putting it in email.

Even though this might lead to multiple different validations? Once for email, once for database insertion? Is it because validations differ varying on the nature of the next course of action? DB vs email?