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

本文详细梳理了PHP在接收不同前端传值(如null、''、'[]'、[]等)时的处理方式,揭示了HTTP协议无法表达数据类型的特性,导致PHP将所有值视为字符串。通过实例分析了jQuery的$.post方法发送不同类型数据到PHP服务器后的实际接收效果,并指出在某些情况下数据可能未被正确传递。此外,还提到了使用CURL进行POST测试的待验证情况,为理解前后端交互提供了深入洞察。
摘要由CSDN通过智能技术生成

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测试
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值