记一次php curl导致的故障

本文描述了在一个特定环境中使用curl请求第三方接口时遇到的问题,即在本地和Alpha环境请求正常,但在Beta环境请求失败的情况。通过分析,发现强制使用IPv4请求可以解决该问题,并提供了修改后的curl配置代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

情景描述

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

转载于:https://blog.51cto.com/13990437/2344025

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值