前言
该代码给有需要的人,需要一点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)");
}
}
}
}