编程技术

PHP 数据传输神器 — cURL

cnguu · 10月25日 · 2018年 ·

官方文档

简单的网页爬虫

<?php
$url = 'https://cnguu.cn';
$curl = curl_init();                              // 初始化
curl_setopt($curl, CURLOPT_URL, $url);            // 需要获取的 URL 地址
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); // 将 curl_exec() 获取的信息以字符串返回,而不是直接输出
$output = curl_exec($curl);                       // 执行
curl_close($curl);                                // 关闭
echo $output;

简单 GET 请求

<?php
function curlGet($url)
{
    $oCurl = curl_init();
    if (stripos($url, 'https://') !== false) {
        curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($oCurl, CURLOPT_SSLVERSION, 1);
    }
    curl_setopt($oCurl, CURLOPT_URL, $url);
    curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1);
    $sContent = curl_exec($oCurl);
    $aStatus = curl_getinfo($oCurl);
    curl_close($oCurl);
    if (intval($aStatus['http_code']) == 200) {
        return json_decode($sContent, true);
    } else {
        return false;
    }
}

简单 POST 请求

<?php
function curlPost($url, $param)
{
    $oCurl = curl_init();
    if (stripos($url, 'https://') !== false) {
        curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($oCurl, CURLOPT_SSLVERSION, 1);
    }
    if (is_string($param) || is_null($param)) {
        $strPOST = $param;
    } elseif (is_array($param)) {
        curl_setopt($oCurl, CURLOPT_HTTPHEADER, ['Content-type: application/json']);
        $strPOST = json_encode($param);
    } else {
        $aPOST = [];
        foreach ($param as $key => $val) {
            $aPOST[] = $key . '=' . urlencode($val);
        }
        $strPOST = join('&', $aPOST);
    }
    curl_setopt($oCurl, CURLOPT_URL, $url);
    curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($oCurl, CURLOPT_POST, true);
    curl_setopt($oCurl, CURLOPT_POSTFIELDS, $strPOST);
    $sContent = curl_exec($oCurl);
    $aStatus = curl_getinfo($oCurl);
    curl_close($oCurl);
    if (intval($aStatus['http_code']) == 200) {
        return json_decode($sContent, true);
    } else {
        return false;
    }
}

GET 下载文件

<?php
function fileGet($url)
{
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_NOBODY, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $package = curl_exec($ch);
    $info = curl_getinfo($ch);
    curl_close($ch);
    return array_merge(['header' => $info], ['body' => $package]);
}

推荐

cURL 工具库:ws-http

0 条回应