php 实现下载apk
PHP 实现下载 APK 文件的方法
设置正确的 HTTP 头部
确保在发送文件内容之前设置正确的 HTTP 头部,告诉浏览器这是一个可下载的文件。通常需要设置 Content-Type 和 Content-Disposition。
header('Content-Type: application/vnd.android.package-archive');
header('Content-Disposition: attachment; filename="example.apk"');
header('Content-Length: ' . filesize($file_path));
读取文件并输出
使用 readfile() 函数读取 APK 文件内容并输出到浏览器,完成下载。

$file_path = '/path/to/your/file.apk';
if (file_exists($file_path)) {
readfile($file_path);
exit;
} else {
echo 'File not found.';
}
完整代码示例
将上述两部分结合,形成完整的下载逻辑。

$file_path = '/path/to/your/file.apk';
if (file_exists($file_path)) {
header('Content-Type: application/vnd.android.package-archive');
header('Content-Disposition: attachment; filename="example.apk"');
header('Content-Length: ' . filesize($file_path));
readfile($file_path);
exit;
} else {
echo 'File not found.';
}
安全性考虑
确保文件路径安全,避免用户通过输入恶意路径下载服务器上的敏感文件。可以使用 basename() 函数过滤文件名。
$file_name = basename($_GET['file']);
$file_path = '/path/to/apks/' . $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 {
echo 'File not found.';
}
处理大文件
对于大文件,可以使用分块读取的方式,避免内存占用过高。
$file_path = '/path/to/large_file.apk';
if (file_exists($file_path)) {
header('Content-Type: application/vnd.android.package-archive');
header('Content-Disposition: attachment; filename="large_file.apk"');
header('Content-Length: ' . filesize($file_path));
$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);
exit;
} else {
echo 'File not found.';
}
通过以上方法,可以高效且安全地实现 PHP 下载 APK 文件的功能。






