我是初学者的 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!";
}
谢谢你!!
https://stackoverflow.com/questions/17289928/