2

We've recently moved servers and have been noticing some weird problems. The main problem that we've noticed is that any variable where a null check is performed in php is being interpreted as a string.

e.g.

    if($var == null){
        //do something
    }

The two key changes that have been made are: 1. Change from HTTP server to HTTPS 2. Change from php version, 5.3.14 to 5.3.13

The requests are made using jQuery.ajax post call.

My question is, are there any known problems/reasons why this is happening (such as the changes above) and is there anything that can be done to resolve the problem (with minimal changes).

As always Thanks for your responses!

Edit: Example

Js/jQuery

    var test = null;
    $.ajax({
        url: 'functions.php',
        data: { action: 'testNullFunction', testVar:test },
        type: 'post',
        success:
        function (output) {
            alert(output)
        }})

Php:

    if (isset($_POST['action']) && !empty($_POST['action'])) {
         $action = $_POST['action'];
         switch ($action) {
             case 'testNullFunction':
                 if ($_POST['testVar']==null || is_null($_POST['testVar'])){
                       echo "its null"; 
                } 
             break;
TStu
  • 244
  • 3
  • 15
  • 2
    Could you show an example of how you set `$var` before testing it against `null`? And if it's a from a request parameter from an Ajax call how is the parameter set in JS/jQuery? – nnnnnn Aug 14 '12 at 00:18
  • 1
    Added an example above @nnnnnn – TStu Aug 14 '12 at 00:35

3 Answers3

5

When you do:

$.ajax({
    url: 'functions.php',
    data: { action: 'testNullFunction', testVar:test },
    type: 'post',
    success: function (output) {
        alert(output)
    }
})

You send the data as a string, thus all values also become strings.

When PHP receives it, it is still a string. It is impossible in this case for the PHP to determine whether testVar contained null or "null" - the type information was lost.


You can fix that by sending:

data: { action: 'testNullFunction', testVar: JSON.stringify(test) }

And receiving:

$testVar = json_decode($_POST['testVar'])
Eric
  • 95,302
  • 53
  • 242
  • 374
2

Somewhat of a naive answer, but try doing strict type checking.

if($var === null){
    //do something
}

Or perhaps use is_null instead.

if (is_null($var)){
    //do something
}
Steven Liao
  • 3,577
  • 3
  • 19
  • 25
2

If you aren't encoding your data along the lines of JSON, your fields will be sent as strings - this includes the null being sent as 'null' and of course if you evaluate against something like if($myVar==null) and $myVar contains 'null' it isn't truly null.

You might also want to look at this question.

Community
  • 1
  • 1
Fluffeh
  • 33,228
  • 16
  • 67
  • 80