In the previous exercise, we performed a simple validation to check the user’s input, but we made a mistake by directly displaying the data we received from them. Remember that we must never simply trust the data we receive from the client. In order to protect against innocent but dangerous user mistakes, malicious users, or man-in-the-middle attacks, we need to sanitize the data—transform it into a safe and standardized format. In this exercise, we’ll focus on making data safe to display on the user’s browser.
PHP provides several built-in functions to help with sanitization:
We can use the built-in PHP
trim() function to remove any whitespace characters from the beginning or end of a string we receive as form input. Though not a security concern, this can help standardize the data prior to validation.
When we want to display the user’s input within our own HTML, we should first run it through
htmlspecialchars(). This built-in function transforms HTML elements into HTML entities (characters that represent HTML elements but won’t display as HTML), so that the PHP interpreter doesn’t recognize them as HTML. This prevents, for example, a man-in-the-middle attack in which malicious HTML is injected into a user’s view of our site.
$data = "<a href=\"https://www.evil-spam.biz/html/\">Your account has been compromised! Click here to get technical support!!</a>"; echo htmlspecialchars($data); // Prints: <a href="https://www.evil-spam.biz/html/">Your account has been compromised! Click here to get technical support!</a>
Sometimes we will also want to perform custom sanitizations that cannot be accomplished with built-in functions, but we’ll discuss these later in the lesson.
Let’s sanitize some data!
Take a look at the form we’ve provided. What happens when you enter
<h1>Hello, world!</h1> into the form and submit it?
Change the provided code such that instead of simply displaying the user’s input, their input is run through the
htmlspecialchars() function before being displayed.
Make sure the change is working as intended by entering
<h1>Hello, world!</h1> into the form and submitting it again.