本文目录导读:

我来详细说明PHP后端开发APP版本检测功能的完整实现方案。
数据库设计
首先创建版本管理表:
CREATE TABLE `app_versions` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`platform` varchar(20) NOT NULL COMMENT '平台: ios/android',
`version_code` int(11) NOT NULL COMMENT '版本号(数字)',
`version_name` varchar(50) NOT NULL COMMENT '版本名称(x.x.x)',
`update_type` tinyint(1) NOT NULL DEFAULT 0 COMMENT '更新类型: 0-可选更新, 1-强制更新, 2-静默更新',
`download_url` varchar(500) NOT NULL COMMENT '下载地址',
`update_desc` text COMMENT '更新说明',
`file_size` varchar(50) DEFAULT NULL COMMENT '文件大小',
`md5` varchar(32) DEFAULT NULL COMMENT '文件MD5校验',
`force_update_version` varchar(50) DEFAULT NULL COMMENT '强制更新最低版本',
`status` tinyint(1) DEFAULT 1 COMMENT '状态: 0-禁用, 1-启用',
`create_time` datetime DEFAULT CURRENT_TIMESTAMP,
`update_time` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
KEY `idx_platform_status` (`platform`, `status`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
版本检测API
<?php
// version_check.php
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
// 获取请求参数
$platform = $_GET['platform'] ?? ''; // ios/android
$current_version = $_GET['version_code'] ?? 0; // 当前版本号
$device_id = $_GET['device_id'] ?? ''; // 设备ID(可选)
// 参数验证
if (empty($platform) || empty($current_version)) {
echo json_encode([
'code' => 400,
'msg' => '参数不完整',
'data' => null
]);
exit;
}
// 连接数据库(示例使用PDO)
try {
$pdo = new PDO('mysql:host=localhost;dbname=app_db', 'root', 'password');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// 获取最新版本信息
$stmt = $pdo->prepare("
SELECT * FROM app_versions
WHERE platform = ? AND status = 1
ORDER BY version_code DESC
LIMIT 1
");
$stmt->execute([$platform]);
$latest_version = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$latest_version) {
echo json_encode([
'code' => 404,
'msg' => '未找到版本信息',
'data' => null
]);
exit;
}
// 比较版本
$has_update = false;
$update_type = 'optional';
if ($current_version < $latest_version['version_code']) {
$has_update = true;
// 判断更新类型
if ($latest_version['update_type'] == 1) {
// 强制更新
$update_type = 'force';
} elseif ($latest_version['update_type'] == 2) {
// 静默更新
$update_type = 'silent';
} else {
// 检查是否需要根据版本号强制更新
if (!empty($latest_version['force_update_version'])) {
$force_version = explode(',', $latest_version['force_update_version']);
if (in_array($current_version, $force_version)) {
$update_type = 'force';
}
}
}
}
// 组装响应数据
$response = [
'code' => 200,
'msg' => 'success',
'data' => [
'has_update' => $has_update,
'update_type' => $update_type,
'version_code' => $latest_version['version_code'],
'version_name' => $latest_version['version_name'],
'download_url' => $latest_version['download_url'],
'update_desc' => $latest_version['update_desc'],
'file_size' => $latest_version['file_size'],
'md5' => $latest_version['md5']
]
];
echo json_encode($response);
} catch (PDOException $e) {
echo json_encode([
'code' => 500,
'msg' => '服务器内部错误',
'data' => null
]);
}
?>
版本发布接口(管理后台)
<?php
// release_version.php
// 安全检查(这里简化,实际需要Token验证)
$token = $_SERVER['HTTP_TOKEN'] ?? '';
if (!checkAdminToken($token)) {
exit(json_encode(['code' => 401, 'msg' => '未授权']));
}
// 接收POST数据
$data = json_decode(file_get_contents('php://input'), true);
// 数据验证
$rules = [
'platform' => 'required|in:ios,android',
'version_name' => 'required|regex:/^\d+\.\d+\.\d+$/',
'version_code' => 'required|integer',
'update_type' => 'required|in:0,1,2',
'download_url' => 'required|url',
'update_desc' => 'required'
];
// 验证函数(简化示例)
function validate($data, $rules) {
foreach ($rules as $field => $rule) {
if (!isset($data[$field])) {
return "缺少字段: $field";
}
// 具体验证逻辑...
}
return true;
}
$validation = validate($data, $rules);
if ($validation !== true) {
echo json_encode(['code' => 400, 'msg' => $validation]);
exit;
}
// 写入数据库
try {
$pdo->beginTransaction();
// 如果发布新版本,可以选择禁用旧版本
if ($data['update_type'] == 1) { // 强制更新
$stmt = $pdo->prepare("
UPDATE app_versions SET status = 0
WHERE platform = ? AND status = 1
");
$stmt->execute([$data['platform']]);
}
// 插入新版本
$stmt = $pdo->prepare("
INSERT INTO app_versions
(platform, version_code, version_name, update_type, download_url, update_desc, file_size, md5, force_update_version)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
");
$stmt->execute([
$data['platform'],
$data['version_code'],
$data['version_name'],
$data['update_type'],
$data['download_url'],
$data['update_desc'],
$data['file_size'] ?? '',
$data['md5'] ?? '',
$data['force_update_version'] ?? ''
]);
$pdo->commit();
echo json_encode([
'code' => 200,
'msg' => '版本发布成功',
'data' => ['id' => $pdo->lastInsertId()]
]);
} catch (Exception $e) {
$pdo->rollBack();
echo json_encode([
'code' => 500,
'msg' => '发布失败: ' . $e->getMessage()
]);
}
?>
优化版本比较逻辑
<?php
// VersionComparator.php
class VersionComparator {
/**
* 版本号转数字比较
*/
public static function versionToCode($versionName) {
$parts = explode('.', $versionName);
$code = 0;
$multiplier = [10000, 100, 1];
foreach ($parts as $i => $part) {
if (isset($multiplier[$i])) {
$code += intval($part) * $multiplier[$i];
}
}
return $code;
}
/**
* 判断是否需要更新
*/
public static function needUpdate($currentVersion, $newVersion, $updateType) {
// 版本比较
$current = self::versionToCode($currentVersion);
$new = self::versionToCode($newVersion);
if ($new <= $current) {
return false;
}
// 根据更新类型返回不同逻辑
switch ($updateType) {
case 0: // 可选更新
return 'optional';
case 1: // 强制更新
return 'force';
case 2: // 静默更新
return 'silent';
default:
return false;
}
}
/**
* 检查是否在强制更新范围内
*/
public static function isInForceRange($currentVersion, $forceVersions) {
$forceList = explode(',', $forceVersions);
$currentCode = self::versionToCode($currentVersion);
foreach ($forceList as $version) {
if (self::versionToCode(trim($version)) == $currentCode) {
return true;
}
}
return false;
}
}
?>
缓存优化
<?php
// 使用Redis缓存版本信息
class VersionCache {
private $redis;
private $cacheKey = 'app_version_';
private $cacheTime = 3600; // 缓存1小时
public function __construct() {
$this->redis = new Redis();
$this->redis->connect('127.0.0.1', 6379);
}
/**
* 获取缓存版本信息
*/
public function getVersion($platform) {
$key = $this->cacheKey . $platform;
$data = $this->redis->get($key);
if ($data) {
return json_decode($data, true);
}
// 从数据库获取
$version = $this->getFromDatabase($platform);
if ($version) {
$this->redis->setex($key, $this->cacheTime, json_encode($version));
}
return $version;
}
/**
* 清除缓存
*/
public function clearCache($platform = null) {
if ($platform) {
$this->redis->del($this->cacheKey . $platform);
} else {
$this->redis->del($this->cacheKey . 'ios');
$this->redis->del($this->cacheKey . 'android');
}
}
}
?>
客户端请求示例
<?php
// Android应用内版本检测
$request_data = [
'platform' => 'android',
'version_code' => 123, // 当前版本号
'device_id' => 'device_123456'
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.yourapp.com/version_check.php');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($request_data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
$result = json_decode($response, true);
if ($result['code'] == 200 && $result['data']['has_update']) {
if ($result['data']['update_type'] == 'force') {
// 强制更新,直接跳转下载
} elseif ($result['data']['update_type'] == 'optional') {
// 可选更新,提示用户
} elseif ($result['data']['update_type'] == 'silent') {
// 静默更新,后台下载
}
}
?>
关键设计要点:
- 版本比较:使用数字版本号便于比较
- 更新类型:支持可选、强制、静默三种更新
- 缓存优化:使用Redis缓存减轻数据库压力
- 安全性:验证请求参数,管理接口需鉴权
- 扩展性:支持MD5校验、文件大小等信息
这样设计的版本检测系统可以满足大多数APP的更新需求,并且易于扩展和维护。