user45678
user45678

Reputation: 341

How to check if $_POST is only whitespace?

I'd like to check if $_POST is only whitespaces in case someone hit the space bar and tried to insert empty records in the database. I'd like to do this server side. I'm already checking if it is empty with if ( ! empty( $_POST ) ) however, this will be bypassed if I hit the spacebar and enter only whitespaces. I have a piece of code below but I was wondering how to verify all of them without having to hard code every input field name?

if ( ! empty( $_POST ) ) {
   if (ctype_space($_POST['first_name'])) { 
      //return to form with error
   }else{
      //insert in db
   }
}

Upvotes: 1

Views: 2407

Answers (3)

mickmackusa
mickmackusa

Reputation: 47904

Never assume that a superglobal element will exist.

First check the element's existence with isset or empty depending on your requirements.

Then check if fully comprised of spaces.

if (empty($_POST['first_name']) || ctype_space($_POST['first_name'])) {
    echo "Missing/Invalid First Name value";
} else {
    echo "Good enough";
}

By doing these things in this order, you avoid generating Notices.

This is lean and direct because the conditions "short circuit" (don't continue evaluating after first failure) and only two function calls are used.

It is a good idea to perform this check on each individual key in your whitelist of expected keys. Then you can deliver specific failure alerts based on your conditional outcomes.

My overarching advice is to concentrate on refining the quality/strength of your validation and ensuring only expected values make it through your screening process and that you are offering clear failure messages to your users.

I mean, think about it, checking a non-empty/non-space-filled value doesn't do great job of validating. If you have other fields where you expect an integer value, check for ctype_digit. If you are validating an email value, use an email validator.

Making DRY code is important but not more important than solid/secure code.

p.s. You will largely improve the UX if you add some client-side validation. If you are using an html form, I recommend packing your fields with attributes like required and pattern. You can offer your users overt guidance with title attributes or a tooltip feature.

Upvotes: 2

Mcsky
Mcsky

Reputation: 1445

Take a look at the trim function

trim — Strip whitespace (or other characters) from the beginning and end of a string

if (!isset($_POST['first_name']) || empty(trim($_POST['first_name']))) {
    //return to form with error
}

With the above snipet, first_name :

  • Have to be in the global $_POST variable

  • Can't be a string with only whitespaces

Upvotes: 6

Mirceac21
Mirceac21

Reputation: 1754

To automatically trim all inputs.

foreach ($_POST as $name => $value) {
    $value = trim($value);
    if (empty($value)) {
        // the value is empty do something with that
    }
}

Upvotes: 2

Related Questions