我是PHP的新手并且尝试了我的手。我正在创建一个文件并写回来。在某个路径中创建一个文件并写入它,对我来说很好。但是,当我尝试从同一个路径下载相同的文件时,它没有被下载而是我得到空文件。
header('Content-type: text/xml');
header("Content-Disposition: attachment; filename=".'check.xml');
header("Content-Length: " . filesize('./download/'.$_SESSION['user_name'].'/check.xml'));
readfile('download/'.$_SESSION['user_name'].'/check.xml');
exit;
嗨,谢谢大家。 但我看到了非常不寻常的事情。当我下载文件时,我没有得到完整的文件。
为什么会出现这种情况
答案 0 :(得分:1)
尝试从文件路径的开头删除./
,如下所示:
header('Content-type: text/xml');
header("Content-Disposition: attachment; filename=".'check.xml');
header("Content-Length: " . filesize('download/'.$_SESSION['user_name'].'/check.xml'));
readfile('download/'.$_SESSION['user_name'].'/check.xml');
exit;
对于Linux文件系统,./
表示根,因此相当于/
,../
表示当前目录上方的目录。最好使用绝对文件路径,但只需删除./
即可。
答案 1 :(得分:0)
您还需要使用flush()
刷新PHP的写缓冲区Here是一个很好的工作函数来下载文件
以下是从该页面改编的版本:
public static function downloadFile($fileName) {
$filePath = $fileName;
$size = filesize($filePath);
// Taken from http://w-shadow.com/blog/2007/08/12/how-to-force-file-download-with-php/
header("Content-type: text/plain");
header("Content-Disposition: attachment; filename=\"$fileName\"");
header("Content-Transfer-Encoding: binary");
header("Accept-Ranges: bytes");
// The three lines below basically make the download non-cacheable
header("Cache-control: private");
header("Pragma: private");
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Content-Length: " . $size);
if ($file = fopen($filePath, "r")) {
$buffer = fread($file, $size); // this only works for small files!
print $buffer;
flush();
fclose($file);
}
}