简体   繁体   English

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

[英]How can I send "special" data in a POST request using PHP

So I found a Python code that is doing what I want to do, but I can't find a way to get it working in PHP (I have tried many times to translate them).所以我找到了一个Python代码,它正在做我想做的事情,但我找不到让它在 PHP 中工作的方法(我已经尝试了很多次来翻译它们)。

Here is the Python code :这是 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))

So, I know the URL, and here, json.dumps(switch)) is {"intrusion_settings": {"active_mode": "away"}}所以,我知道 URL,在这里, json.dumps(switch)){"intrusion_settings": {"active_mode": "away"}}

How can I do this in PHP?我怎样才能在 PHP 中做到这一点? I tried many many ways, but nothing worked.我尝试了很多很多方法,但没有任何效果。 Even when the request was sent successfully, it wasn't working.即使请求成功发送,它也不起作用。

If you want to go deeper in what I am trying to do, here is the python code that I want to do in PHP: https://github.com/dynasticorpheus/gigasetelements-cli (only the switch_modus part)如果你想更深入地了解我想要做的事情,这里是我想用 PHP 做的 python 代码: https://github.com/dynasticorpheus/gigasetelements-cli : https://github.com/dynasticorpheus/gigasetelements-cli (只有 switch_modus 部分)

Thank you if you can help!如果你能帮忙,谢谢!

You have to use json_encode function.您必须使用json_encode函数。


Example例子

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

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

Possible solution可能的解决方案

$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);

Manual手动的

Executable code 可执行代码

PHP: json_encode PHP:json_encode

PHP: cURL PHP:卷曲

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM