gpt4 book ai didi

php - 强制文件下载代码在本地主机上工作,但在 php 中的实际服务器上不工作

转载 作者:行者123 更新时间:2023-12-05 08:00:48 24 4
gpt4 key购买 nike

我是初学者的 php 程序员。我已经编写代码来下载任何类型的文件。

当我点击下载链接时,它会转到 download.php 文件。我在本地服务器上工作,但不在服务器上工作。

我的代码是:

header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream'); //application/force-download
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
//header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);
exit();

是我的代码有误还是服务器需要一些设置?

最佳答案

这是在线测试的代码,它工作正常。你可以试试这个

$folder_name = $_GET['fol_name'];
$file_directory = "../img/files/$folder_name"; //Name of the directory where all the sub directories and files exists

$file = $_GET['file_name']; //Get the file from URL variable

$file_array = explode('/', $file); //Try to seperate the folders and filename from the path
$file_array_count = count($file_array); //Count the result
$filename = $file_array[$file_array_count-1]; //Trace the filename
$file_path = dirname(__FILE__).'/'.$file_directory.'/'.$file; //Set the file path w.r.t the download.php... It may be different for u

if(file_exists($file_path)) {
header("Content-disposition: attachment; filename={$filename}"); //Tell the filename to the browser
header('Content-type: application/octet-stream'); //Stream as a binary file! So it would force browser to download
readfile($file_path); //Read and stream the file
}
else {
echo "Sorry, the file does not exist!";
}

谢谢你!!

关于php - 强制文件下载代码在本地主机上工作,但在 php 中的实际服务器上不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17289928/

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