-1

I want to learn if a string is null in PHP, I am using this code.

UPDATE: Working code, thanks for all your help.

<?php

    //Syntax blah.php?request=Value to log here

    //iPwnStore
    $request = $_GET['iPwnStore'];
    if(empty($request)) 
    {
        echo "Error, string is null!"; 
        //It always comes done to the Error, allthough $request isn't nil
    }
    else 
    {
        file_put_contents('iPwnStore.txt', $request1."\n\n", FILE_APPEND);
        echo "Success";
    }
?>
2
  • 1
    You're setting $request1, but checking $request.
    – Barmar
    Oct 26, 2013 at 10:22
  • 1
    This question appears to be off-topic because reading the code properly would reveal the error.
    – vascowhite
    Oct 26, 2013 at 11:27

5 Answers 5

3

Edit: You have a mismatched variable name...

$request1 = $_GET['iPwnStore'];
echo $request; 

$request1 should be $request

if ($request === null)

Or

if (empty($request))
3
  • what about using isset also.... Oct 26, 2013 at 10:42
  • Yes, this would also be a good option.
    – Gavin
    Oct 26, 2013 at 11:24
  • OK, thanks if(empty($request) worked for me Oct 26, 2013 at 16:15
1

That way:

if( $request === null ) {
...

or by using is_null() function: http://php.net/is_null

0

As already suggested $request === null, but a better solution is to check if $_GET['iPwnStore'] is set using

if (isset($_GET['iPwnStore']) {
    // Add to file
} else {
    // Show some error
}

otherwise calling $request = $_GET['iPwnStore'] will produce a notice.

0

It depends on what you're trying to accomplish.

If you want to check if the string is null (explicitly NULL, not ''), you should use: (note the strict type comparison operator: ===, more on that here: php comparison operators)

if ($request === NULL) {
   ...
}

If you want to prevent putting empty content into files (ie. you want to check if string is empty) you should use this: (note that you need to do explicit typecasting to string, to prevent situation, where $request is an integer 0, in which case empty($request) will return TRUE. For more on that read here: php empty function

$request = (string) $request;
if (empty($request)) {
   ...
}
0
<?php
  $request1 = $_GET['iPwnStore'];
  echo $request;
  if($request != '' ) 
  {
      //do something
  } else 
  {
      //do something
  }
?>

This should do the job.

1
  • Won't work... $resquest1 set but $request used in comparison.
    – Gavin
    Oct 26, 2013 at 10:27

Not the answer you're looking for? Browse other questions tagged or ask your own question.