Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Null being sent as a string "null"

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;
like image 879
TStu Avatar asked Sep 23 '26 23:09

TStu


2 Answers

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'])
like image 64
Eric Avatar answered Sep 25 '26 13:09

Eric


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
}
like image 33
Steven Liao Avatar answered Sep 25 '26 12:09

Steven Liao



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!