• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

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

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

 场景:在调用第三方接口时经常需要使用到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;
    }
}

调用如下:

<?

$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来获取,代码:

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

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

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

 '{"hello":"world","lang":"php"}' (length=30)

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
开发自己PHPMVC框架(一)发布时间:2022-07-10
下一篇:
PHP文件上传实现的注意点发布时间:2022-07-10
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap