PHP接收前端传值各种情况整理

服务端代码:


header('Access-Control-Allow-Origin:*');
var_dump($_POST);
exit;

情况

1) 传null


$.post('http://xxxxx.xx/index.php', {
    "test": null
}, function(data, status) {
    console.log(data);
});

结果:


array(1) {
  ["test"]=>
  string(0) ""
}

2) 传''

代码:


$.post('http://xxxxx.xx/index.php', {
    "test": ''
}, function(data, status) {
    console.log(data);
});

结果:


array(1) {
  ["test"]=>
  string(0) ""
}

3) 传'[]'


$.post('http://xxxxx.xx/index.php', {
    "test": '[]'
}, function(data, status) {
    console.log(data);
});

结果:


array(1) {
  ["test"]=>
  string(2) "[]"
}

4) 传[]


$.post('http://xxxxx.xx/index.php', {
    "test": []
}, function(data, status) {
    console.log(data);
});

结果:


array(0) {
}

5) 传2个[]


$.post('http://xxxxx.xx/index.php', {
    "test": [],
    "test2": []
}, function(data, status) {
    console.log(data);
});

结果:


array(0) {
}

6) 传{}


$.post('http://xxxxx.xx/index.php', {
    "test": {}
}, function(data, status) {
    console.log(data);
});

结果:


array(0) {
}

7) 传2个{}


$.post('http://xxxxx.xx/index.php', {
    "test": {},
    "test2": {}
}, function(data, status) {
    console.log(data);
});

结果:


array(0) {
}

8) 传1个{}加1个非空对象


$.post('http://xxxxx.xx/index.php', {
    "test": {},
    "test2": {"a": 1}
}, function(data, status) {
    console.log(data);
});

结果:


array(1) {
  ["test2"]=>
  array(1) {
    ["a"]=>
    string(1) "1"
  }
}

9) 传[{}]


$.post('http://xxxxx.xx/index.php', {
    "test": [{}]
}, function(data, status) {
    console.log(data);
});

结果:


array(0) {
}

10) 传[[{}]]


$.post('http://xxxxx.xx/index.php', {
    "test": [[{}]]
}, function(data, status) {
    console.log(data);
});

结果:


array(0) {
}

11) 传'nil'


$.post('http://xxxxx.xx/index.php', {
    "test": 'nil'
}, function(data, status) {
    console.log(data);
});

结果:


array(1) {
  ["test"]=>
  string(3) "nil"
}

12) 传0


$.post('http://xxxxx.xx/index.php', {
    "test": 0
}, function(data, status) {
    console.log(data);
});

结果:


array(1) {
  ["test"]=>
  string(1) "0"
}

13) 传'null'


$.post('http://xxxxx.xx/index.php', {
    "test": 'null'
}, function(data, status) {
    console.log(data);
});

结果:


array(1) {
  ["test"]=>
  string(4) "null"
}

用抓包工具发现

  1. http请求里面并不会发送"无效的"字段——[]和{},所以不是PHP丢弃了,而是没收到;
  2. 当传的值是js里的null,会转换成空字符串,http请求里面是test=,所以PHP接收到的test是个空字符串;
  3. http协议不能表示值是什么类型,所以PHP只能什么都当做string

总结:

  1. PHP对于接收到的每一个值,会转换成字符串变量
  2. PHP对于接收到的,之所有会接收不到是因为被一系列规则过滤掉了

以上结论是在jQ和PHP7之下验证的,其他环境不一定保证正确,之后可以试验使用CURL发送数据试试。

TODO:

  • [ ] 用CURL发送POST测试

原文链接:https://my.oschina.net/wiiilll/blog/3002507