Php: Keep same filename when downloading from server
I'm downloading a file through php script and everything work perfectly except one ugly truth. The downloaded file keep the same url and with original name appended. How do I maintain the same filename when file downloaded?
http://bachday.com/index.php?page=custom&file=mmailer/download.php?mfile=sample.docx
if (isset($_GET['mfile'])) { $file = $_SERVER['DOCUMENT_ROOT'].'/oc-content/plugins/mmailer/pfile/'.$_GET['mfile']; if (file_exists($file) && is_readable($file) && preg_match('/.docx$/',$file)) { header('Content-Type: application/docx'); header("Content-Disposition: attachment; filename="$file""); readfile($file); /* header("Expires: 0"); header("Cache-Control: no-cache, must-revalidate"); header("Pragma: no-cache"); echo (readfile($file));*/ } else { header("HTTP/1.0 404 Not Found"); echo "Error 404: File Not Found:
$file"; }
header('Content-Disposition: attachment; filename="name_of_file_here"')
would have done the trick. You are passing the full path of the file there as header("Content-Disposition: attachment; filename="$file"");
since your $file contains full path. Instead just send the name of the file.
header('Content-Disposition: attachment; filename='.basename($file));
这条线可以解决这个问题。
if (isset($_GET['mfile'])) {
$file = $_SERVER['DOCUMENT_ROOT'].'/oc-content/plugins/mmailer/pfile/'.$_GET['mfile'];
if (file_exists($file) && is_readable($file) && preg_match('/.docx$/',$file)) {
header('Content-Type: application/docx');
header("Content-Disposition: attachment; filename="".basename($file).""");//use basename to extract filename from full file path
readfile($file);
/*
header("Expires: 0");
header("Cache-Control: no-cache, must-revalidate");
header("Pragma: no-cache");
echo (readfile($file));*/
}
else
{
header("HTTP/1.0 404 Not Found");
echo "Error 404: File Not Found:
$file";
}
链接地址: http://www.djcxy.com/p/46674.html
上一篇: 使用angularjs从PHP REST API下载docx文件
下一篇: Php:从服务器下载时保留相同的文件名