php中使用curl来post一段json数据

 场景:在调用第三方接口时经常需要使用到curl进行数据交互,在初次使用时遇到一些小问题,记录下来随时查阅。

封装curl相关方法便于使用,方法如下:

复制代码
/**
 * @param $url
 * @param string $error
 * @param array|string $post
 * @param int $timeout
 * @param null $ref
 * @param string $ua
 * @param $contentType
 * @return bool|mixed
 */
function xcurl($url, &$error = "", $post = array(), $timeout = 5, $ref = null, $ua = "Mozilla/5.0 (X11; Linux x86_64; rv:2.2a1pre) Gecko/20110324 Firefox/4.2a1pre", $contentType) {
    $ch           = curl_init();

    if(!empty($ref)) {
        curl_setopt($ch, CURLOPT_REFERER, $ref);
    }

    curl_setopt($ch, CURLOPT_AUTOREFERER, true);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
    curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);

    if (false !== stripos($url, "https://")) {                # https处理,不校验相关证书
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    }

    if(!empty($ua)) {
        curl_setopt($ch, CURLOPT_USERAGENT, $ua);
    }

    if(count($post) > 0){
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
    }

    if ('json' == $contentType) {
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Content-Length: ' . strlen($post)));
    }

    $output       = curl_exec($ch);
    if ($output === false) {
        $error    = curl_error($ch);
        curl_close($ch);
        return false;
    } else {
        curl_close($ch);
        return $output;
    }
}
复制代码

调用如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
<?
 
$url = 'localhost/php/server.php';
$error = '';
$post = [
    'hello' => 'world',
    'lang' => 'php',
];
$post = json_encode($post);
 
$result = xcurl($url,$error, $post, 5, null, 'Mozilla/5.0 (X11; Linux x86_64; rv:2.2a1pre) Gecko/20110324 Firefox/4.2a1pre', 'json');
 
var_dump($result);

本地服务接受参数时遇到了问题,无论$_POST还是$_REQUEST都无法获取curl客户端发送的json,所以改用file_get_contents来获取,代码:

1
print_r(file_get_contents('php://input'));

最终请求curl.php获取到结果为:

/code/php/curl.php:19:string

 '{"hello":"world","lang":"php"}' (length=30)
posted @   郭延龙  阅读(896)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 25岁的心里话
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示