1. 程式人生 > >記一次php curl導致的故障

記一次php curl導致的故障

query rto res 設置 getc ont info transfer lin

情景描述

本地和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"}‘

記一次php curl導致的故障