如何使用PHP在POST请求中发送“特殊”数据

2024-09-30 02:23:26 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我找到了一个Python代码,它正在做我想做的事情,但是我找不到一种方法让它在PHP中工作(我已经尝试过多次翻译它们)

以下是Python代码:

def restpost(url, payload, head=None):

   if head is not None:
      r = s.post(url, data=payload, timeout=90, stream=False, headers=head, verify=pem)
   else:
      r = s.post(url, data=payload, timeout=90, stream=False, verify=pem)
   commit_data = r.json()
   return commit_data 


restpost(URL, json.dumps(switch))

所以,我知道URL,这里,json.dumps(switch)){"intrusion_settings": {"active_mode": "away"}}

如何在PHP中实现这一点?我尝试了很多方法,但都不管用。即使请求成功发送,它也无法工作

如果您想更深入地了解我正在尝试做的事情,下面是我想在PHP中执行的python代码:https://github.com/dynasticorpheus/gigasetelements-cli(仅限切换部分)

如果你能帮忙,谢谢你


Tags: 方法代码nonejsonfalseurldatastream
1条回答
网友
1楼 · 发布于 2024-09-30 02:23:26

您必须使用json_encode函数


示例

<?php
$arr = [
        "intrusion_settings" => [
            "active_mode" => "away"
    ]
];

echo json_encode($arr); // {"intrusion_settings":{"active_mode":"away"}}

可能的解决方案

$url='URL';
$payload = [
        "intrusion_settings" => [
            "active_mode" => "away"
    ]
];

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type:application/json']);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
// curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); // add this line if you have problem with SSL
// curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); // add this line if you have problem with SSL

/**
You might need those lines for your .pem certification files
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
    curl_setopt($ch, CURLOPT_VERBOSE, true);
    curl_setopt($ch, CURLOPT_CAINFO, __DIR__.'/yourcertfilename.pem');
    curl_setopt($ch, CURLOPT_CAPATH, __DIR__.'/yourcertfilename.pem');
*/
$result = curl_exec($ch);
curl_close($ch);

print_r($result);

手册

Executable code

PHP: json_encode

PHP: cURL

相关问题 更多 >

    热门问题