PHP

PHP - cURL 使用DEMO、并发请求

2019-05-15  本文已影响118人  达莎雕
<?php
/**
 * curl上传文件
 * @param  服务器地址      $uploadTo  string
 * @param  本地文件路径   $filePath    string
 * @return array
 */
function upload($filePath, $uploadTo, $name) {
    $ch = curl_init();
    if (class_exists('CURLFile')) {
        $data = ['upload' => new CURLFile($filePath, '', $name)];
    } else {
        $data = ['upload' => '@' . $filePath, 'name' => $name];
    }
    curl_setopt($ch, CURLOPT_URL, $uploadTo);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
    curl_setopt($ch, CURLOPT_POST,true);
    curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}
class Http
{
    public function curlRequest($url, $data=[], $header=[], $ignoreSsl=0, $timeout=30) {
        $curl = curl_init();
        // request url
        curl_setopt($curl, CURLOPT_URL, $url);
        // headers
        if(!empty($header)) curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        // post fields
        if (!empty($data)) { // post方式
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
        // https
        if (!empty($ignoreSsl)) {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        }
        // timeout
        curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, $timeout);
        curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);

        $output = curl_exec($curl);
        if (curl_error($curl)) $output = curl_error($curl);
        curl_close($curl);
        return $output;
    }

    /**
     * curl下载文件
     * @param string $url 下载文件地址
     * @param string $saveFlder 下载文件保存目录
     * @param string $filename 下载文件保存名称
     * @return bool
     */
    public function curlLoadFile($url, $saveFlder, $ext) {
        // curl 获取文件内容
        $content = $this->curlRequest($url, '', '', 1);
        $filename = md5(mt_rand() . time() . uniqid('load_file', true)) . $ext;
        $savePath = $saveFlder . $filename;
        // 保存文件到制定路径
        $putRes = file_put_contents($savePath, $content);
        if (!$putRes) return false;
        return $savePath;
    }

    public function curlLoadFileWithName($url, $savePath)     {
        // curl 获取文件内容
        $content = $this->curlRequest($url, '', '', 1);
        // 保存文件到制定路径
        $putRes = file_put_contents($savePath, $content);
        if (!$putRes) return false;
        return $savePath;
    }
}
<?php
function curlMultiReq($urls, $uSeconds=100) {
    $handle=[];
    $running = 0;
    $waitUsecs = intval($uSeconds);
    $mulCh = curl_multi_init();
    foreach($urls as $key => $url) {
        $ch = initCurl($url);
        curl_multi_add_handle($mulCh, $ch);
        $handle[$key] = $ch;
    }
    // 执行请求
    do {
        curl_multi_exec($mulCh, $running);
        if ($waitUsecs > 0) usleep($waitUsecs); // 250000 = 0.25 sec
        echo "not finish request num :" . $running . PHP_EOL; // 查看当前还未结束的请求数量
    } while ($running > 0);
    // 获取返回的内容
    $response = [];
    foreach($handle as $i => $ch) {
        $response[] = curl_multi_getcontent($ch);
        curl_multi_remove_handle($mulCh, $ch);
    }
    curl_multi_close($mulCh);
    return $response;
}

function initCurl($url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); // 302 redirect
    curl_setopt($ch, CURLOPT_MAXREDIRS, 7); // maximum number of redirects allowed
    return $ch;
}
// 测试代码
<?php
$urls = [
    'http://api.map.baidu.com/telematics/v3/weather?location=%E5%98%89%E5%85%B4&output=json&ak=5slgyqGDENN7Sy7pw29IUvrZ',
    'http://api.map.baidu.com/telematics/v3/weather?location=%E5%98%89%E5%85%B4&output=json&ak=5slgyqGDENN7Sy7pw29IUvrZ',
    'http://api.map.baidu.com/telematics/v3/weather?location=%E5%98%89%E5%85%B4&output=json&ak=5slgyqGDENN7Sy7pw29IUvrZ',
    'http://api.map.baidu.com/telematics/v3/weather?location=%E5%98%89%E5%85%B4&output=json&ak=5slgyqGDENN7Sy7pw29IUvrZ',
];
$res = curlMultiReq($urls);
print_r($res);
// 测试结果
not finish request num :4
not finish request num :4
...
not finish request num :4
not finish request num :4
...
not finish request num :1
not finish request num :1
not finish request num :0
Array
(
    [0] => {"status":201,"message":"APP被用户自己禁用,请在控制台解禁"}
    [1] => {"status":201,"message":"APP被用户自己禁用,请在控制台解禁"}
    [2] => {"status":201,"message":"APP被用户自己禁用,请在控制台解禁"}
    [3] => {"status":201,"message":"APP被用户自己禁用,请在控制台解禁"}
)
上一篇 下一篇

猜你喜欢

热点阅读