最近在做人工智能人脸识别的小程序,每张照片都应有一个唯一的字符串。这里我们采用guid来生成唯一的字符串。
// 生成guid
function guid(){
if (function_exists('com_create_guid')) {
return com_create_guid();
}else{
mt_srand((double)microtime()*10000);
$charid = strtoupper(md5(uniqid(rand(),true)));
$hyphen = chr(45);
$uuid = chr(123)
.substr($charid,0,8).$hyphen
.substr($charid,8,4).$hyphen
.substr($charid,12,4).$hyphen
.substr($charid,16,4).$hyphen
.substr($charid,20,12)
.chr(125);
return $uuid;
}
}
// 生成可用的guid
function myguid(){
$guid = guid();
$guid = trim($guid,'{}');
$guid = str_replace('-', '_', $guid);
return $guid;
}
然后写请求,获取access_token,我们发现百度云给的代码有些不对,我给大家分享一下正确的代码,代码如下:
function https_post($url = '', $param = '') {
// return 123;
if (empty($url) || empty($param)) {
return false;
}
$postUrl = $url;
$curlPost = $param;
$curl = curl_init();//初始化curl
curl_setopt($curl, CURLOPT_URL,$postUrl);//抓取指定网页
curl_setopt($curl, CURLOPT_HEADER, 0);//设置header
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
curl_setopt($curl, CURLOPT_POST, 1);//post提交方式
curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost);
curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,false);
curl_setopt($curl,CURLOPT_SSL_VERIFYHOST,false);
curl_setopt($curl,CURLOPT_SSLVERSION,1);
$data = curl_exec($curl);//运行curl
curl_close($curl);
return $data;
}
function access_token(){
$file= __DIR__.'.\access_token';
if(file_exists($file)){
$str=file_get_contents($file);
try{
$arr=json_decode($str,true);
if(is_array($arr)){
$totime=$arr['totime'];
if($totime>time()){
return $arr['access_token'];
}
}
}catch(Exception $e){
}
}
$url = 'https://aip.baidubce.com/oauth/2.0/token';
$post_data['grant_type'] = 'client_credentials';
$post_data['client_id'] = 'xx';
$post_data['client_secret'] = 'xx';
$o = "";
foreach ( $post_data as $k => $v )
{
$o.= "$k=" . urlencode( $v ). "&" ;
}
$post_data = substr($o,0,-1);
$res = https_post($url, $post_data);
$arr=json_decode($res,true);
if(isset($arr['access_token']) && isset($arr['expires_in'])){
$data['access_token']=$arr['access_token'];
$data['totime']=time()+$arr['expires_in']-3600;
file_put_contents($file,json_encode($data));
return $arr['access_token'];
}else{
return false;
}
}
我把access_token放在了一个文件中,存储起来。
我在后台调用了这些方法,代码如下:
public function facevalid(){
$token = access_token();
// echo $token;
$file = './Uploads/1.jpg';
if (!file_exists($file)) {
die('文件不存在!');
}
$url="https://aip.baidubce.com/rest/2.0/face/v2/detect?access_token=".$token;
$img=file_get_contents($file);
$img=base64_encode($img);
// echo $img;
$bodys=array(
'max_face_num'=>5,
'face_fileds'=>"age,beauty,expression,faceshape,gender,galsses,landmark,race,qualities",
'image'=>$img
);
$res=request_post($url,$bodys);
echo $res;
}
}
这些代码就可以检测人脸是否存在。