Remove White Space from Form Data to Avoid Potential Headaches

When processing form submissions, it's important to remove white space before and after each value. Those extra spaces will likely go unnoticed by most visitors, but luckily this won't be a problem most of the time. In some cases, however, those spaces can lead to a lot of confusion.


Let's say our website requires visitors to log in before viewing certain content. The website also has a password creation form. If someone enters "MyPassword " into this form, they'll likely have problems later. Well, problems beyond the less than secure password. Logging in with "MyPassword" is going to cause frustration since the extra space is missing.

Of course, many forms employ validation and sanitation techniques when processing passwords. For example, the password may be checked so that it only contains certain characters. White space is one of the characters typically not allowed. If an unacceptable character is found, an error like "Your password can only contain letters and numbers" may be displayed. If the visitor didn't know they typed the space character, confusion about the error message will ensue.


Removing these extra spaces is simple. PHP's trim() function removes all leading and trailing spaces.

$_POST['password'] = 'MyPassword ';
var_dump($_POST['password']); //OUTPUT: string(11) "MyPassword "
$_POST['password'] = trim($_POST['password']);
var_dump($_POST['password']); //OUTPUT: string(10) "MyPassword"

The function isn't always needed. When collecting website comments, for example, extra spaces likely won't matter. But then again, using trim() probably isn't going to hurt anything either. Using the function every time we process form input guarantees that our values get trimmed when truly needed.

Another thing to keep in mind is that forms typically have required fields. These fields need to be completed before the form can be submitted. We may do something like the following to prevent blank values:

if(empty($_POST['name'])) {
     //name is empty, display error

If " " is entered for the name, the field won't be empty. Preventing bogus values like this can be accomplished by running the POST variable through trim() before the if test.


When filling in forms, chances are that visitors will unintentionally enter extra spaces before or after form fields. These extra spaces can prove detrimental to the operation of a website. They are also easy to avoid with trim().


There are currently no comments.

Leave a Comment