Chapter 16. Validation and Error Handling

We’ve already discussed performing validation within our PHP code. In this chapter we’ll explore our options for validating form data before a form submission. We’ll also discuss what to do when validation fails, and how to process other errors. We can check information on the client side in the user’s browser with JavaScript. We can also check the data when it’s submitted directly in PHP.

There’s some information that can go out as part of a production error message that isn’t harmful for end users. For example, it’s OK to say that you’re having a problem connecting to your database. However, you don’t want to reveal more information than is necessary in any error messages that may go out to end users. You don’t want to disclose the IP address of your database and certainly not the username that was attempted when you tried to connect. Both of those could aid a potential attacker in breaking into the database when it comes back online.

Validating User Input with JavaScript

On the client side, your best tool for validating data is JavaScript. JavaScript is different than PHP because it’s designed to execute in the user’s browser instead of on the server. Because it executes from the client’s computer, JavaScript isn’t allowed to access anything that could be a security risk, such as the local filesystem or network resources. JavaScript is primarily used in web pages. Although its name sounds like Java, it has no relationship to it.

Since this ...

Get Learning PHP & MySQL, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.