gpt4 book ai didi

php - 如何强制下载不同类型的扩展文件php

转载 作者:行者123 更新时间:2023-12-02 04:11:22 25 4
gpt4 key购买 nike

我有一个脚本,用户可以在其中上传任何类型的文件,并且我也将他们的扩展名类型存储在数据库中,但是我如何强制下载具有相应扩展名的文件

这是我试过的

$filename = $file; // this can be in any format may be zip or maybe mp3

$path = "/home/tw/public_html/file/"; //path of this file
$fullPath = $path.$filename; //path to download file

$filetypes = $extension; // it is the extension of current file

if ($fd = fopen ($fullPath, "r")) {
if (!in_array(substr($filename, -3), $filetypes)) {
echo "Invalid download State.";
exit;
}
$fsize = filesize($fullPath);
$path_parts = pathinfo($fullPath);

header("Content-type: application/zip");
header("Content-Disposition: filename=".$path_parts["basename"]."");
header("Content-length: $fsize");
header("Cache-control: private"); //use this to open files directly
while(!feof($fd)) {
$buffer = fread($fd, 2048);
echo $buffer;
}
}
fclose ($fd);
exit;

扩展名可以是任何东西

 'application/x-bittorrent',
'application/x-bzip',
'application/x-bzip2',
'application/x-compressed',
'application/x-excel',
'application/x-gzip',
'audio/*',
'image/*',
'multipart/x-gzip',
'multipart/x-zip',
'text/plain',
'text/rtf',
'text/richtext',
'text/xml',
'video/*',
'text/csv',
'jpg' => 'image/jpeg',
'jpeg' => 'image/jpeg',
'jpe' => 'image/jpeg',
'gif' => 'image/gif',
'png' => 'image/png',
'bmp' => 'image/bmp',
'flv' => 'video/x-flv',
'js' => 'application/x-javascript'

最佳答案

强制下载任何文件扩展名。您可以先读取文件并将该文件写入输出缓冲区以供下载。

这是下载文件的代码。希望它也能帮助解决您的问题。

此代码基于:http://php.net/manual/en/function.readfile.php

<?php
// You can used any file extension to output the file for download
$file = 'monkey.gif';

if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
readfile($file);
exit;
}
?>

关于php - 如何强制下载不同类型的扩展文件php,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38180690/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com