php 下载apk实现
使用 PHP 下载 APK 文件
通过 PHP 实现 APK 文件下载需要设置正确的 HTTP 头信息,确保文件以附件形式传输,并处理文件流。以下是具体实现方法:
设置正确的 HTTP 头信息
确保浏览器识别文件为 APK 并触发下载:
header('Content-Type: application/vnd.android.package-archive');
header('Content-Disposition: attachment; filename="app.apk"');
header('Content-Length: ' . filesize($file_path));
读取文件并输出到客户端
使用 readfile() 函数高效传输文件内容:

$file_path = '/path/to/your/app.apk';
if (file_exists($file_path)) {
readfile($file_path);
exit;
} else {
header("HTTP/1.0 404 Not Found");
echo "File not found.";
}
处理大文件的分块传输
对于大文件,使用分块读取避免内存问题:
$chunk_size = 1024 * 1024; // 1MB per chunk
$handle = fopen($file_path, 'rb');
while (!feof($handle)) {
echo fread($handle, $chunk_size);
ob_flush();
flush();
}
fclose($handle);
安全注意事项

-
验证文件路径防止目录遍历攻击:
$base_dir = '/secure/apk/storage/'; $file_path = realpath($base_dir . basename($_GET['file'])); if (strpos($file_path, $base_dir) !== 0) { die("Invalid file path"); } -
限制下载频率防止滥用:
session_start(); if ($_SESSION['last_download'] > time() - 3600) { die("Download limit exceeded"); } $_SESSION['last_download'] = time();
完整示例代码
结合上述要点的基础实现:
<?php
$file_name = 'app.apk';
$file_path = __DIR__ . '/downloads/' . $file_name;
if (file_exists($file_path)) {
header('Content-Type: application/vnd.android.package-archive');
header('Content-Disposition: attachment; filename="' . $file_name . '"');
header('Content-Length: ' . filesize($file_path));
readfile($file_path);
exit;
} else {
http_response_code(404);
echo "APK file not available";
}
?>






