记一次php curl导致的故障

情景描述

本地和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

curl -4 url -X POST -H "Content-Type:application/json" -d '{"app_id":"ceshi","secret_key":"123456"}'

猜你喜欢

转载自blog.51cto.com/13990437/2344025