wmSafe致力于互联网资源
道可道,非恒道,名可名,非恒名

【PHP】PHP并发请求多个API并获取结果通用代码,适配7.x和8.x,给有需要的朋友

本文最后更新于2024-9-26,已经有47 天没有更新,如果文章内容或图片资源失效,请留言反馈,我们会及时处理,谢谢!

【PHP】PHP并发请求多个API并获取结果通用代码,适配7.x和8.x,给有需要的朋友

前言

该代码给有需要的人,需要一点php基础,也方便后续要用直接copy


function echo_eror($code, $msg)
{
    $data = array('code' => $code, 'message' => $msg);
    $jsonData = json_encode($data);
    header('Content-Type: application/json');
    echo $jsonData;
    exit();
}

function postMultipleUrls($urls, $base64Image) {
    $multiCurl = curl_multi_init();
    $curlHandles = [];
    $responses = [];

    foreach ($urls as $urlConfig) {
        $curl = curl_init();
        $data = $urlConfig['data'];

        $paramKey = $urlConfig['param_key'] ?? 'img';
        $data[$paramKey] = $base64Image;

        curl_setopt($curl, CURLOPT_URL, $urlConfig['url']);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_TIMEOUT, 6);
        curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 6);

        curl_multi_add_handle($multiCurl, $curl);
        $curlHandles[$urlConfig['url']] = $curl;
    }

    $running = null;
    do {
        curl_multi_exec($multiCurl, $running);
        curl_multi_select($multiCurl);
    } while ($running > 0);

    foreach ($curlHandles as $url => $curl) {
        $responses[$url] = curl_multi_getcontent($curl);
        curl_multi_remove_handle($multiCurl, $curl);
        curl_close($curl);
    }

    curl_multi_close($multiCurl);
    return $responses;
}

$apiConfigs = [
    [
        'url' => "https://apis.tianapi.com/imgcensor/index",
        'data' => ['key' => 'xxxx'],
        'param_key' => 'img'
    ],
    [
        'url' => "https://route.showapi.com/1201-1?appKey=xxxx",
        'data' => ['appKey' => 'xxxx'],
        'param_key' => 'base64'
    ],
];

//图片base64
base64Image = '';

//多线程并发调用多个API
$results = postMultipleUrls($apiConfigs, $base64Image);

foreach ($results as $url => $result) {
    $json = json_decode($result, true);

    if (strpos($url, 'tianapi.com') !== false) {
        if ($json['code'] == 200) {
            if ($json['result']['conclusionType'] != 1) {
                echo_eror(405, "图片违规,请重新选取图片上传 (来源: tianapi)");
            }
        }
    }

    if (strpos($url, 'showapi.com') !== false) {
        if($json['showapi_res_code'] == 0 && $json['showapi_res_body']['ret_code'] == 0){
            if ($json['showapi_res_body']['code'] != 'normal') {
                echo_eror(405, "图片违规,请重新选取图片上传 (来源: showapi)");
            }
        }
    }
}
本原创文章未经允许不得转载 | 若要转载请注明出处,否则将承担相应的法律责任!
本文链接: https://blog.wm404.com/2024/09/26/c54e485f.html
赞赏排名 赞赏支持

评论

  • captcha
暂无评论,要不来一发?

您的关注就是我们最大的支持

联系我们 关于我们