PHP 如何将curl代码转换成curl命令

应用场景:

        将PHPcurl请求代码转换成Linux可执行的curl命令,可返回连接时间与响应时间。

实现过程: 

<?php
    function convertToCurl($method, $url, $data = null, $headers = array()) {
        $command = 'curl -w "\ntime_connect: %{time_connect}\ntime_starttransfer: %{time_starttransfer}\ntime_total: %{time_total}\n" -X ' . $method;
        // 添加 URL
        $command .= ' \'' . $url . '\'';
        // 添加请求头
        foreach ($headers as $header) {
            $command .= ' -H \'' . $header . '\'';
        }
        // 添加请求数据
        if (!empty($data)) {
            if ($method === 'POST') {
                // 根据 Content-Type 头部选择适当的处理方式
                $contentType = '';
                foreach ($headers as $header) {
                    if (strpos($header, 'Content-Type') !== false) {
                        $contentType = $header;
                        break;
                    }
                }
                if (strpos($contentType, 'application/json') !== false) {
                    // Content-Type 为 application/json,将请求数据转换为 JSON 格式
                    $postData = json_encode($data);
                    $command .= ' -d \'' . $postData . '\'';
                } else {
                    // 其他类型的 Content-Type,将数组转换为查询字符串
                    $postData = http_build_query($data);
                    $command .= ' --data \'' . $postData . '\'';
                }
            } else {
                // GET 请求时将数据作为查询字符串拼接到 URL
                $query = http_build_query($data);
                $command .= ' \'' . $url . '?' . $query . '\'';
            }
        }
        return $command;
    }


    $method = 'POST';
    $url = 'http://192.168.0.125/api/hsm/sym/symEncryptInternalForKEK';
    $postData = [
        'keyIndex' => 1,
        "iv" => '22222222222222222222',
        "plainData" => '111111111111111'
    ];
    $json_data = json_encode($postData);
    $headers = array(
        "Content-Type: application/json; charset=utf-8",
        "Content-Length:".strlen($json_data)
    );
     
    $curlCommand = convertToCurl($method, $url, $postData, $headers);
    echo $curlCommand;

效果展示:

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值