php 实现下载apk
使用 PHP 实现 APK 文件下载
通过 PHP 实现 APK 文件下载的核心是设置正确的 HTTP 头信息,并输出文件内容。以下是一个完整的实现方法。
设置 HTTP 头信息
确保客户端正确识别文件类型并触发下载行为,需设置以下头信息:

Content-Type: 指定为application/vnd.android.package-archiveContent-Disposition: 强制浏览器下载而非直接打开Content-Length: 指定文件大小
header('Content-Type: application/vnd.android.package-archive');
header('Content-Disposition: attachment; filename="example.apk"');
header('Content-Length: ' . filesize('/path/to/example.apk'));
读取并输出文件内容
使用 readfile() 函数高效输出文件内容到客户端:
readfile('/path/to/example.apk');
exit;
完整代码示例
将上述步骤合并为一个可执行的 PHP 文件:

<?php
$file_path = '/path/to/example.apk';
if (file_exists($file_path)) {
header('Content-Type: application/vnd.android.package-archive');
header('Content-Disposition: attachment; filename="' . basename($file_path) . '"');
header('Content-Length: ' . filesize($file_path));
readfile($file_path);
exit;
} else {
http_response_code(404);
echo 'File not found';
}
?>
安全注意事项
为确保下载过程安全可靠,建议添加以下防护措施:
- 验证文件路径防止目录遍历攻击
- 限制访问权限确保只有授权用户可下载
- 对下载请求进行日志记录
$file_path = realpath('/safe/directory/' . basename($_GET['file']));
if (strpos($file_path, '/safe/directory/') !== 0) {
die('Invalid file path');
}
性能优化建议
对于大文件下载,考虑使用分块传输:
$chunk_size = 1024 * 1024;
$handle = fopen($file_path, 'rb');
while (!feof($handle)) {
echo fread($handle, $chunk_size);
ob_flush();
flush();
}
fclose($handle);
这种方法能有效降低服务器内存消耗,特别适合大体积 APK 文件的传输。






