人脸识别-获取access_token

首先,在common里面创建一个function.php文件

time()) {
                  return $arr['access_token'];
                  exit;
                }
            }
        }catch(Exception $e){

        }
    }

    $url = 'https://aip.baidubce.com/oauth/2.0/token';  
    $post_data['grant_type']       = 'client_credentials';  
    $post_data['client_id']      = '你自己的client_id';  
    $post_data['client_secret'] = '你自己的client_secret';  
    $o = "";  
    foreach ( $post_data as $k => $v )   
    {  
        $o.= "$k=" . urlencode( $v ). "&" ;  
    }  
    $post_data = substr($o,0,-1);  
      
    $res = request_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;
    }
 
// return  json_decode($res,true); //注意需要转换一下  
}   
 ?>

然后在index控制器中调用access_token方法

//人脸检测
	 public function facevalid(){
	 	//获取access_token
	 	$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);
	 	$bodys=array(
	 		'max_face_num'=>5,
	 		'face_fields'=>"age,beauty,expression,faceshape,gender,glasses,landmark,race,qualities",
	 		'image'=>$img
	 		);
	 	$res=request_post($url,$bodys);
	 	echo $res;
	 }

在浏览器中运行facevalid方法,就可以获取人脸信息。


你可能感兴趣的:(获取access_token)