0

Possible Duplicate:
Check whether $_POST-value is empty

I am using this code to validate if the passed input is not empty, but this fails when I use "white space" in the input. It does pass the empty() check.

if (empty($_POST['r_user'])) {
    $data['error'] = 'Please pick a username to continue.';
    $data['errorID'] = 'r_user';
}

What is the proper method to check an empty string in PHP?

Community
  • 1
  • 1
Ahmed Fouad
  • 2,963
  • 10
  • 30
  • 54

7 Answers7

4

You need to use trim function before checking the variable.

$trimUser= trim ($_POST['r_user']);

now execute the empty method.

BenMorel
  • 34,448
  • 50
  • 182
  • 322
RK.
  • 973
  • 5
  • 19
  • 45
2

as per PHP documentation suggestion, your code would become:

if (trim($_POST['r_user']) == false) {
    $data['error'] = 'Please pick a username to continue.';
    $data['errorID'] = 'r_user';
}
Alex
  • 23,004
  • 4
  • 39
  • 73
1

you can trim() removes white space from the beginning and end of a string

working example

      $test = "      ";
      if(trim($test)){
         if (empty($test))
             echo "true";
         else
             echo "false";
      }

live : check this on codepad

NullPoiиteя
  • 56,591
  • 22
  • 125
  • 143
0

You can use trim nicely here, it removes whitespace front and back:

if (empty(trim($_POST['r_user']))) { // Incorrect!

Edit, wow, learned a new thing today.

This will however work:

$var=trim($_POST['r_user']);
if (empty($var)) {

Working Example:

 <?php 
    $var='    ';
    $var=trim($var);
    if(empty($var))
        echo "Yay";
    else
        echo "Nay!";

 ?>

Output:

Yay

Fluffeh
  • 33,228
  • 16
  • 67
  • 80
0
if ( empty( trim( $_POST['r_user'] ))) { 

// wrong! gives an error - learned something new :) // the right way should be :

$myvar = trim( $_POST['r_user'] ); 

if ( empty( $myvar )) { 

or

if ( trim( $_POST['r_user'] ) != '' ) {
OctoD
  • 365
  • 5
  • 13
0

You may use :

$var = '';
if (array_key_exists('r_user', $_POST)) {
  $var = trim($_POST['r_user']);
} 
if (empty($var)) {
   // do some stuffs
}

instead.

Alain Tiemblo
  • 36,099
  • 17
  • 121
  • 153
-1
if(isset($_POST['r_user'])){
           // ur code
           }
EbinPaulose
  • 1,129
  • 3
  • 14
  • 26