php curl 请求接口

192次阅读
没有评论
//function
function http_request($url, $data=null) {
    // 第一步:创建 curl
    $ch = curl_init();
    // 第二步:设置 curl
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 禁止服务器端校检 SSL 证书
    // 判断 $data 数据是否为空
    if(!empty($data)) {
        // 模拟发送 POST 请求
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    }
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 以文档流的形式返回数据
    // 第三步:执行 curl
    $output = curl_exec($ch);
    // 第四步:关闭 curl
    curl_close($ch);
    // 把 $output 当做返回值返回
    return $output;
}

// 获取客户端 ip
function get_client_ip(){
    $headers = ['HTTP_X_REAL_FORWARDED_FOR',
        'HTTP_X_FORWARDED_FOR',
        'HTTP_CLIENT_IP',
        'REMOTE_ADDR'
    ];
    foreach ($headers as $h){// var_dump($_SERVER);
        $ip = @ $_SERVER[$h];
        // 有些 ip 可能隐匿,即为 unknown
        if (isset($ip) && strcasecmp($ip, 'unknown') ){break;}
    }
    if($ip){
        // 可能通过多个代理,其中第一个为真实 ip 地址
        list($ip) = explode(',', $ip, 2);// 最多拿两个值
    }
    return $ip;
}

/**
 * curl 简单封装
 * @param $url
 * @param bool $params
 * @param int $ispost
 * @param int $https
 * @return bool|mixed
 */
function curl($url, $params = false, $ispost = 0, $https = 0)
{$httpInfo = array();
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36');
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    if ($https) {curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); // 对认证证书来源的检查
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); // 从证书中检查 SSL 加密算法是否存在
    }
    if ($ispost) {curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
        curl_setopt($ch, CURLOPT_URL, $url);
    } else {if ($params) {if (is_array($params)) {$params = http_build_query($params);
            }
            curl_setopt($ch, CURLOPT_URL, $url . '?' . $params);
        } else {curl_setopt($ch, CURLOPT_URL, $url);
        }
    }

    $response = curl_exec($ch);

    if ($response === FALSE) {//echo "cURL Error:" . curl_error($ch);
        return false;
    }
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $httpInfo = array_merge($httpInfo, curl_getinfo($ch));
    curl_close($ch);
    return $response;
}
正文完
有偿技术支持加微信
post-qrcode
 
评论(没有评论)
验证码