温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

记一次php curl导致的故障

发布时间:2020-07-09 22:07:50 来源:网络 阅读:923 作者:juggles 栏目:开发技术

情景描述

本地和alpha环境curl请求第三方接口正常
beta环境curl请求失败

代码如下

public static function getCurl($url, $type = 'get', $data = '', $decode = true, $header = array())
    {
        $ch = curl_init();    // 初始化CURL句柄
        curl_setopt($ch, CURLOPT_TIMEOUT, 5);//设置超时3秒钟
        curl_setopt($ch, CURLOPT_URL, $url); //设置请求的URL
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // 设为TRUE把curl_exec()结果转化为字串,而不是直接输出
        if (strtolower($type) == 'post') {
            curl_setopt($ch, CURLOPT_POST, 1); //启用POST提交
            is_array($data) && $data = http_build_query($data);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data); //设置POST提交的字符串
        }
        if (!empty($header)) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        }

        $document = curl_exec($ch); //执行预定义的CURL
        $info     = curl_getinfo($ch, CURLINFO_HTTP_CODE); //得到返回信息的特性
        curl_close($ch);
        if ($info >= 200 && $info < 300) {
            if ($decode) {
                return json_decode($document, true);
            }
            return $document;
        } else {
            return array("result" => "fail", "cause" => $document);
        }
    }

解决方案

强制使用IPV4请求

curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);

curl配置说明:
http://php.net/manual/zh/function.curl-setopt.php

补充

curl 命令行进行请求

-4 代表使用IPV4
-d 传递数据,json形式的'{"app_id":"ceshi","secret_key":"123456"}',form形式的"app_id=ceshi&secret_key=123456"
-X POST形式
-H 设置请求头

curl -4 url -X POST -H "Content-Type:application/json" -d '{"app_id":"ceshi","secret_key":"123456"}'
向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI