本文展示了如何在PHP中集成腾讯云人脸识别服务,并将结果写入数据库。通过调用腾讯云的API,获取人脸识别Token,处理返回结果,并更新用户信息到本地数据库。文章还包括错误处理和数据库操作的最佳实践,确保身份验证的安全性和有效性。
<?php
require "./vendor/autoload.php";
use TencentCloud\Common\Credential;
use TencentCloud\Common\Profile\ClientProfile;
use TencentCloud\Common\Profile\HttpProfile;
use TencentCloud\Common\Exception\TencentCloudSDKException;
use TencentCloud\Faceid\V20180301\FaceidClient;
use TencentCloud\Faceid\V20180301\Models\DetectAuthRequest;
use TencentCloud\Faceid\V20180301\Models\GetDetectInfoEnhancedRequest;
// 获取配置项
function C($name){
$config = [
"TX_ID" => "AKIDNbdZKEyXxBByd7OSM3WourPo11Cdt4A",
"TX_KEY" => "5KWcebP2a4QegcP1XyOgqwu3JPTN6gO3"
];
return $config[$name] ?? null;
}
// 获取人脸识别结果
function getResult($BizToken = "") {
if (empty($BizToken)) {
return [
'ErrCode' => -1,
'ErrMsg' => 'BizToken 参数无效',
];
}
$params = [
'Action' => 'GetDetectInfoEnhanced',
'Version' => '2018-03-01',
'BizToken' => $BizToken,
'RuleId' => '1',
];
try {
$cred = new Credential(C("TX_ID"), C("TX_KEY"));
$httpProfile = new HttpProfile();
$httpProfile->setEndpoint("faceid.tencentcloudapi.com");
$clientProfile = new ClientProfile();
$clientProfile->setHttpProfile($httpProfile);
$client = new FaceidClient($cred, "", $clientProfile);
$req = new GetDetectInfoEnhancedRequest();
$req->fromJsonString(json_encode($params));
$resp = $client->GetDetectInfoEnhanced($req);
$result = json_decode($resp->toJsonString(), true);
return $result['Text'] ?? [
'ErrCode' => -1,
'ErrMsg' => '未能获取有效值',
];
} catch (TencentCloudSDKException $e) {
return [
'ErrCode' => -1,
'ErrMsg' => $e->getMessage(),
];
}
}
// 处理数据库更新逻辑
function updateMemberInfo($id, $real_name, $idc) {
$db = include("./Application/Common/Conf/db.php");
$mysqli = new mysqli("127.0.0.1", $db["DB_USER"], $db["DB_PWD"], $db["DB_NAME"], 3306);
if ($mysqli->connect_error) {
die("数据库连接失败: " . $mysqli->connect_error);
}
$sql = "UPDATE dt_member SET real_name = ?, idc = ? WHERE id = ?";
$stmt = $mysqli->prepare($sql);
if ($stmt === false) {
die("SQL 语句准备失败: " . $mysqli->error);
}
$stmt->bind_param("ssi", $real_name, $idc, $id);
if ($stmt->execute()) {
echo "更新成功!";
header('Location: /index.php/Home/Member/info.html');
} else {
echo "更新失败: " . $stmt->error;
}
$stmt->close();
$mysqli->close();
}
// 执行人脸认证结果处理
$bizToken = $_GET["BizToken"] ?? null;
$result = getResult($bizToken);
if ($result["ErrCode"] == 0) {
$id = $_GET["Extra"];
$real_name = $result["Name"];
$idc = $result["OcrIdCard"];
updateMemberInfo($id, $real_name, $idc);
} else {
exit("人脸认证失败: " . $result["ErrMsg"]);
}
// 获取腾讯云人脸认证 Token
function getToken($IdCard = '', $Name = "", $notify = "", $uid = 0) {
if (empty($IdCard) || empty($Name) || empty($uid)) {
exit("参数错误");
}
$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? "https://" : "http://";
$url = $protocol . $_SERVER['HTTP_HOST'] . "/idc2.php";
$params = [
'Action' => 'DetectAuth',
'Version' => '2018-03-01',
'RuleId' => "1",
'IdCard' => $IdCard,
'Name' => $Name,
'RedirectUrl' => $url,
'Extra' => $notify,
];
try {
$cred = new Credential(C("TX_ID"), C("TX_KEY"));
$httpProfile = new HttpProfile();
$httpProfile->setEndpoint("faceid.tencentcloudapi.com");
$clientProfile = new ClientProfile();
$clientProfile->setHttpProfile($httpProfile);
$client = new FaceidClient($cred, "", $clientProfile);
$req = new DetectAuthRequest();
$req->fromJsonString(json_encode($params));
$resp = $client->DetectAuth($req);
return json_decode($resp->toJsonString(), true);
} catch (TencentCloudSDKException $e) {
return [
'ErrCode' => -1,
'ErrMsg' => $e->getMessage(),
];
}
}
// 获取 UID 并发起认证
$uid = $_GET["uid"] ?? null;
if ($uid) {
$data = ['idc' => 'your_idc_value', 'real_name' => 'your_real_name'];
$res = getToken($data['idc'], $data['real_name'], $uid);
if (isset($res["Url"])) {
header('Location: ' . $res["Url"]);
} else {
var_dump($res);
}
} else {
exit("UID 参数无效");
}
优化要点:
- 减少重复代码:移除了重复的
require
和use
语句,组织结构更简洁。 - 错误处理改进:通过检查参数和返回结果,优化了错误处理,确保每次出错时有明确的提示。
- 数据库操作改进:增加了数据库操作的错误处理机制,确保数据库连接和 SQL 操作的安全性和可读性。
- 变量安全性:使用了三元运算符或
isset
来确保获取参数时的安全性。
文章:PHP 集成腾讯云人脸识别与数据库操作的实现
在现代 Web 应用开发中,身份验证的需求逐渐从传统的密码验证转向更先进的生物识别技术,比如人脸识别。本文将展示如何在 PHP 中集成腾讯云人脸识别服务,并将结果写入数据库。这个过程包括与腾讯云 API 的交互、处理返回数据,并将身份验证结果存储到本地数据库中。
步骤 1:准备环境
首先,确保你已经安装了 PHP 和 Composer,并通过 Composer 安装了腾讯云的 SDK。运行以下命令:
composer require tencentcloud/tencentcloud-sdk-php
接下来,确保你已经在腾讯云中开通了相关的 API 服务,并获得了相应的 TX_ID
和 TX_KEY
。
步骤 2:集成腾讯云人脸识别
在 PHP 中,我们需要通过腾讯云的 SDK 与 API 交互。这里展示了如何生成人脸识别 Token 并发起认证:
function getToken($IdCard = '', $Name = "", $notify = "", $uid = 0) {
if (empty($IdCard) || empty($Name) || empty($uid)) {
exit("参数错误");
}
$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? "https://" : "http://";
$url = $protocol . $_SERVER['HTTP_HOST'] . "/idc2.php";
$params = [
'Action' => 'DetectAuth',
'Version' => '2018-03-01',
'RuleId' => "1",
'IdCard' => $IdCard,
'Name' => $Name,
'RedirectUrl' => $url,
'Extra' => $notify,
];
try {
$cred = new Credential(C("TX_ID"), C("TX_KEY"));
$httpProfile = new HttpProfile();
$httpProfile->setEndpoint("faceid.tencentcloudapi.com");
$clientProfile = new ClientProfile();
$clientProfile->setHttpProfile($httpProfile);
$client = new FaceidClient($cred, "", $clientProfile);
$req = new DetectAuthRequest();
$req->fromJsonString(json_encode($params));
$resp = $client->DetectAuth($req);
return json_decode($resp->toJsonString(), true);
} catch (TencentCloudSDKException $e) {
return [
'ErrCode' => -1,
'ErrMsg' => $e->getMessage(),
];
}
}
通过上面的代码,我们可以生成 BizToken
,并将用户重定向到腾讯云的验证页面。
步骤 3:处理验证结果
在用户完成验证后,腾讯云将返回结果。我们需要解析返回数据并存储到数据库中:
function getResult($BizToken = "") {
if (empty($BizToken)) {
return [
'ErrCode' => -1,
'ErrMsg' => 'BizToken 参数无效',
];
}
$params = [
'Action' => 'GetDetectInfoEnhanced',
'Version' => '2018-03-01',
'BizToken' => $BizToken,
'RuleId' => '1',
];
try {
$cred = new Credential(C("TX_ID"), C("TX_KEY"));
$httpProfile = new HttpProfile();
$httpProfile->setEndpoint("faceid.tencentcloudapi.com");
$clientProfile = new ClientProfile();
$clientProfile->setHttpProfile($httpProfile);
$client = new FaceidClient($cred, "", $clientProfile);
$req = new GetDetectInfoEnhancedRequest();
$req->fromJsonString(json_encode($params));
$resp = $client->GetDetectInfoEnhanced($req);
$result = json_decode($resp->toJsonString(), true);
return $result['Text'] ?? [
'ErrCode' => -1,
'ErrMsg' => '未能获取有效值',
];
} catch (TencentCloudSDKException $e) {
return [
'ErrCode' => -1,
'ErrMsg' => $e->getMessage(),
];
}
}
步骤 4:更新数据库
我们将识别到的身份信息(如真实姓名和身份证号)存储到本地数据库中:
function updateMemberInfo($id, $real_name, $idc) {
$db = include("./Application/Common/Conf/db.php");
$mysqli = new mysqli("127.0.0.1", $db["DB_USER"], $db["DB_PWD"], $db["DB_NAME"], 3306);
if ($mysqli->connect_error) {
die("数据库连接失败: " . $mysqli->connect_error);
}
$sql = "UPDATE dt_member SET real_name = ?, idc = ? WHERE id = ?";
$stmt = $mysqli->prepare($sql);
if ($stmt === false) {
die("SQL 语句准备失败: " . $mysqli->error);
}
$stmt->bind_param("ssi", $real_name, $idc, $id);
if ($stmt->execute()) {
echo "更新成功!";
header('Location: /index.php/Home/Member/info.html');
} else {
echo "更新失败: " . $stmt->error;
}
$stmt->close();
$mysqli->close();
}
结论
通过使用腾讯云的 SDK 与 PHP 结合,我们可以实现简单的人脸识别与身份验证流程,确保用户的身份信息在验证后能够被安全地写入数据库。这种集成方式不仅可以提升应用的安全性,还能大大简化用户的认证流程。
这种方法可以广泛应用于登录验证、身份核实等场景,为企业和开发者提供更先进的身份管理工具。