我创建了一个文件,使用fopen('contacts','w')。 现在我想提示用户保存这个文件,他想在他的本地机器(使用PHP)。在php中保存由fopen()函数创建的文件?
任何建议或示例代码将不胜感激。
谢谢!
我创建了一个文件,使用fopen('contacts','w')。 现在我想提示用户保存这个文件,他想在他的本地机器(使用PHP)。在php中保存由fopen()函数创建的文件?
任何建议或示例代码将不胜感激。
谢谢!
假设你的文件 - “接触”是一个物理文件是否存在,现在在服务器中。
<?php
$file = 'contacts.csv';
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);
exit;
}
?>
它看起来像我到底想要什么,但是我的文件是“contacts.csv”,那么我应该使用哪种联系方式用于CSV文件? – Bharat 2012-07-30 09:06:19
感谢NinethSense,现在它适合我! – Bharat 2012-07-30 10:02:20
内容类型没问题。只需使用文件名作为contacts.csv。编辑代码。 – NinethSense 2012-07-30 11:23:04
下载代码
<?php
// place this code inside a php file and call it f.e. "download.php"
$path = $_SERVER['DOCUMENT_ROOT']."/path2file/"; // change the path to fit your websites document structure
$fullPath = $path.$_GET['download_file'];
if ($fd = fopen ($fullPath, "r")) {
$fsize = filesize($fullPath);
$path_parts = pathinfo($fullPath);
$ext = strtolower($path_parts["extension"]);
switch ($ext) {
case "pdf":
header("Content-type: application/pdf"); // add here more headers for diff. extensions
header("Content-Disposition: attachment; filename=\"".$path_parts["basename"]."\""); // use 'attachment' to force a download
break;
default;
header("Content-type: application/octet-stream");
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;
// example: place this kind of link into the document where the file download is offered:
// <a href="download.php?download_file=some_file.pdf">Download here</a>
?>
什么由本地机器是什么意思? – Saurabh 2012-07-30 08:49:45
他要保存文件的目录。我想要做同样的事情,比如当我们下载一个文件时,它会提示我们保存文件。 – Bharat 2012-07-30 08:53:39