PHP中Curl调用set_system_time API参数传递问题求助
问题分析与解决方案
你的问题大概率出在参数类型不匹配和请求配置缺失上,结合官方JS示例和你的PHP代码,整理出关键问题点及修正方案:
核心问题点
- 参数类型不符:官方JS示例传递的是数字类型的时间参数(
day: 10),但你手动构造的JSON把所有参数写成了字符串("day":"1"),多数API会严格校验参数类型,这会直接导致请求被拒绝。 - 未显式指定POST请求:虽然设置
CURLOPT_POSTFIELDS会让Curl默认使用POST,但显式声明CURLOPT_POST能避免环境或版本差异引发的请求方法错误。 - 未排查API返回信息:你注释掉了
$result = curl_exec($ch1);,无法获取API返回的错误提示,这是定位问题的核心依据。 - 手动构造JSON易出错:手动拼接JSON字符串容易出现转义、格式错误,应该用PHP内置的
json_encode()生成标准JSON。
修正后的完整代码
<?php $cookie = "cookie.txt"; $ch = curl_init(); // 登录获取会话令牌 curl_setopt($ch, CURLOPT_URL, 'http://192.168.5.23/login.fcgi'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_POST, 1); // 用json_encode生成登录参数,避免手动转义错误 $loginData = json_encode([ "login" => "admin", "password" => "senha" ]); curl_setopt($ch, CURLOPT_POSTFIELDS, $loginData); curl_setopt($ch, CURLOPT_TIMEOUT, 60); curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie); curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie); $headers = [ 'Accept: application/json', 'Authorization: xxxxxxxxxxxxxxxxxxxxxxxxxxxxx', 'Content-Type: application/json' ]; curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); $result = curl_exec($ch); if (curl_errno($ch)) { die('Curl错误:' . curl_error($ch)); } curl_close($ch); $session1 = json_decode($result); if (empty($session1->session)) { die('获取会话令牌失败,返回内容:' . $result); } $sessao = $session1->session; echo "会话令牌:{$sessao}\n"; // 调用设置系统时间API $ch1 = curl_init(); curl_setopt($ch1, CURLOPT_URL, "http://192.168.5.23/set_system_time.fcgi?session={$sessao}"); curl_setopt($ch1, CURLOPT_RETURNTRANSFER, true); // 显式设置POST请求 curl_setopt($ch1, CURLOPT_POST, 1); // 用json_encode生成数字类型的参数,匹配官方示例 $timeData = json_encode([ "day" => 1, "month" => 2, "year" => 2020, "hour" => 21, "minute" => 20, "second" => 22 ]); curl_setopt($ch1, CURLOPT_POSTFIELDS, $timeData); curl_setopt($ch1, CURLOPT_TIMEOUT, 60); curl_setopt($ch1, CURLOPT_COOKIEJAR, $cookie); curl_setopt($ch1, CURLOPT_COOKIEFILE, $cookie); curl_setopt($ch1, CURLOPT_HTTPHEADER, $headers); // 执行请求并获取返回结果 $result1 = curl_exec($ch1); if (curl_errno($ch1)) { die('设置时间Curl错误:' . curl_error($ch1)); } curl_close($ch1); // 打印API返回结果,用于排查问题 echo "API返回结果:{$result1}\n"; ?>
额外排查建议
- 执行代码后查看
API返回结果,如果API返回错误信息(比如参数类型错误),可以直接定位问题。 - 检查会话令牌有效性:登录后打印
$result确认返回的令牌格式是否正确,避免令牌过期或解析错误。 - 对比请求差异:用抓包工具对比PHP请求和官方JS请求的头信息、请求体,确认是否存在格式或内容差异。
内容的提问来源于stack exchange,提问作者murilo
相关产品推荐
相关产品推荐

