用PHP调用聚合数据证件识别接口,识别本地图片
前置条件
在开始前,请作如下准备:
1.学会用PHP输出“Hello World”
2.去 聚合数据 申请证件识别专用的KEY:https://www.juhe.cn/docs/api/id/153
操作步骤
1.配置好PHP开发环境
2.在相应的本地网站根目录下新建一个文件夹并命名为:card
3.请准备一张jpg格式的身份证照片(本示例中的图片来自网络),并命名为1.jpg,放在card目录
4.请务必确保PHP对1.jpg有读权限(先用fopen('1.jpg', 'r')测试一下)
5.在card目录新建一个index.php文件,并输入以下内容:/**<br>
* 证件识别接口示例<br>
* 提供两种方式,请根据您的PHP版本、服务器环境等因素选择适合的方式<br>
* 推荐使用第一种(PHP 5 >= 5.5.0)<br>
* 示例中的身份证图片来自网络,用真实的身份证图片会有更佳的识别效果<br>
*/<br>
<br>
header("Content-type:text/html;charset=utf-8");<br>
$config = array(<br>
'key' => '将我替换成您申请的KEY',<br>
//聚合数据证件识别接口的URL地址<br>
'url' => 'http://v.juhe.cn/certificates/query.php',<br>
//证件的类型,这里是身份证正面<br>
'type' => 'image/jpg',<br>
//证件图片的类型<br>
'cardType' => '2',<br>
);<br>
<br>
/*第一种方式*/<br>
$ch = curl_init($config['url']);<br>
//$filename <p> Path to the file which will be uploaded.</p>
<br>
//$postname [optional] <p>Name of the file.</p>
<br>
$cfile = curl_file_create('filename.jpg', $config['type'], 'postname.jpg');<br>
$data = array(<br>
'cardType' => $config['cardType'],<br>
'key' => $config['key'],<br>
'pic' => $cfile,<br>
);<br>
curl_setopt($ch, CURLOPT_POST,1);<br>
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);<br>
//已经获取到内容,还没输出,如果不加下面这行,则不需要echo response<br>
//curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);<br>
curl_exec($ch);<br>
curl_close($ch);<br>
<br>
/*/第一种方式*/<br>
<br>
/*第二种方式*/<br>
$data = array(<br>
'cardType' => $config['cardType'],<br>
'key' => $config['key'],<br>
'pic' => "@1.jpg",<br>
);<br>
post($config['url'], $data);<br>
/*/第二种方式*/<br>
<br>
function post($url, $data) {<br>
$ch = curl_init();<br>
curl_setopt( $ch , CURLOPT_POST , true );<br>
@curl_setopt( $ch , CURLOPT_POSTFIELDS , $data);<br>
curl_setopt($ch, CURLOPT_URL, $url);<br>
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);<br>
$response = curl_exec($ch);<br>
curl_close($ch);<br>
echo $response;<br>
}
6.打开浏览器,访问http://localhost/card/index.php,正常情况下你应该看到类似下面的内容:{"error_code":"200","reason":"操作成功","result":{"住址":"XX省XX县XX村XX号","保留":"","公民身份号码":"420188195408288888","出生":"1954-08-28","头像":"","姓名":"XXX","性别":"女","民族":"汉族"}}<br>
{"error_code":"200","reason":"操作成功","result":{"住址":"XX省XX县XX村XX号","保留":"","公民身份号码":"420188195408288888","出生":"1954-08-28","头像":"","姓名":"XXX","性别":"女","民族":"汉族"}}
7.如果PHP版本低于5.5,但是又想用curl_file_create,请参考官方文档提供的方法:http://php.net/manual/en/function.curl-file-create.phpFor PHP
<br>
<?php <br />
<br>
if (!function_exists('curl_file_create')) {<br>
function curl_file_create($filename, $mimetype = '', $postname = '') {<br>
return "@$filename;filename="<br>
. ($postname ?: basename($filename))<br>
. ($mimetype ? ";type=$mimetype" : '');<br>
}<br>
}<br>
<br>
?>