因此,我发现了一个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
(仅switch_modus部分)谢谢您的帮助!
最佳答案
您必须使用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
关于python - 如何使用PHP在POST请求中发送“特殊”数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59524010/