【问题标题】:Save a file created by fopen() function in php?在 php 中保存由 fopen() 函数创建的文件?
【发布时间】:2012-07-30 08:47:04
【问题描述】:

我创建了一个文件,使用 fopen('contacts','w')。 现在我想提示用户将此文件保存在他的本地机器中他想要的位置(使用 php)。

任何建议或示例代码将不胜感激。

谢谢!!

【问题讨论】:

  • 本地机器是什么意思?
  • 他要保存文件的目录。我想做同样的事情,比如当我们下载文件时,它会提示我们保存文件。

标签: php fopen


【解决方案1】:

假设您的文件 - “联系人”是一个物理文件,现在存在于服务器中。

<?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;
}
?> 

参考:http://php.net/manual/en/function.readfile.php

【讨论】:

  • 这似乎正是我想要的,但我的文件是“contacts.csv”,那么我应该为 CSV 文件使用什么联系人类型?
  • 内容类型很好。只需使用文件名作为contacts.csv。修改了代码。
【解决方案2】:

下载代码

<?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>
?>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多