Windows命令行cURL传JSON至PHP,PHP获取变量始终为null
问题:POST JSON数据到PHP脚本无法获取内容
环境与操作信息
- 系统:Windows 11
- cURL版本:
curl 8.4.0 (Windows) libcurl/8.4.0 Schannel WinIDN Release-Date: 2023-10-11 Protocols: dict file ftp ftps http https imap imaps pop3 pop3s smtp smtps telnet tftp Features: AsynchDNS HSTS HTTPS-proxy IDN IPv6 Kerberos Largefile NTLM SPNEGO SSL SSPI threadsafe Unicode UnixSockets - 执行的cURL命令:
curl -X POST -H "Content-Type: application/json" -d '{"name":"John Doe","age":30,"city":"New York"}' http://myserver/hello.php - 尝试的PHP脚本(注释为已测试的方法,目标是直接获取JSON而非URL参数):
<?php //header('content-type: application/json'); //$json = file_get_contents('php://input'); //$data = var_dump(json_decode($json, true)); //$data = var_dump(json_decode($_GET, true)); $data = json_decode(file_get_contents('php://input'), true); //$data = json_decode($_POST); //$data = $_POST; //$dump = print_r($data); //$dump = print_r($data); //$arrayJSON = json_decode($str_json); //$data = json_decode($_POST); file_put_contents('test.txt', $data['name']); ?>
问题现象
执行curl命令无报错,PHP脚本可正常调用,但始终无法获取传入的JSON数据,http和https协议均测试过,结果一致。
解决方案
先验证原始输入是否到达
修改脚本,先保存原始输入内容并排查JSON解析错误:<?php $rawInput = file_get_contents('php://input'); file_put_contents('raw_input.txt', $rawInput); $data = json_decode($rawInput, true); if ($data) { file_put_contents('test.txt', $data['name'] ?? '未找到name字段'); } else { file_put_contents('error_log.txt', json_last_error_msg()); } ?> 执行curl后查看`raw_input.txt`和`error_log.txt`,判断是数据未传输到服务器,还是JSON格式解析失败。修复Windows CMD的引号问题
Windows CMD对单引号支持不佳,原命令中的单引号可能导致JSON格式被破坏。改用双引号包裹JSON,内部双引号用反斜杠转义:curl -X POST -H "Content-Type: application/json" -d "{\"name\":\"John Doe\",\"age\":30,\"city\":\"New York\"}" http://myserver/hello.php更稳妥的方式是用文件传递JSON:
新建data.json文件写入{"name":"John Doe","age":30,"city":"New York"},执行:curl -X POST -H "Content-Type: application/json" -d @data.json http://myserver/hello.php检查PHP配置与服务器过滤
- 确认
post_max_size配置值,确保JSON数据大小未超过限制 - 用
curl -v查看请求详情,确认服务器是否存在重定向(部分服务器会将POST转为GET,导致数据丢失):curl -v -X POST -H "Content-Type: application/json" -d @data.json http://myserver/hello.php
- 确认
内容的提问来源于stack exchange,提问作者Jim Dandy BOA
相关产品推荐
相关产品推荐

