使用thinkPHP框架 来获取人脸识别的token。
在application中的common中新建一个function.php
/获取access_token
function request_post($url = '', $param = '') {
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'];
exit;
}
}
}catch(Exception $e){
}
}
$apikey="你的apikey";
$secretkey="你的secretkey";
$url = 'https://aip.baidubce.com/oauth/2.0/token';
$post_data['grant_type'] = 'client_credentials';
$post_data['client_id'] = $apikey;
$post_data['client_secret'] = $secretkey;
$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;
}
// var_dump($res);
}
2. home的index控制器中
public function upload($id=''){ //上传图片
$upload = new \Think\Upload();// 实例化上传类
$upload->maxSize = 3145728 ;// 设置附件上传大小
$upload->exts = array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
$upload->rootPath = './Uploads/'; // 设置附件上传根目录
$upload->savePath = ''; // 设置附件上传(子)目录
// 上传单个文件
$info = $upload->uploadOne($_FILES['file']);
if(!$info) {// 上传错误提示错误信息
return $this->ajaxReturn(array('error'=>true,'msg'=>$upload->getErroe()));
}else{// 上传成功 获取上传文件信息
// echo $info['savepath'].$info['savename'];
return $this->ajaxReturn(array('error'=>false,'msg'=>$info['savepath'].$info['savename'],'id'=>$id));
}
}
//人脸检测
public function facevalid(){
$token = access_token();//获取的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;//输出图片检测出的信息
}