【问题标题】:Unable to make a file auto-download from an FTP server when script is run运行脚本时无法从 FTP 服务器自动下载文件
【发布时间】:2013-08-07 16:37:03
【问题描述】:

我正在尝试编写一个 PHP 页面,该页面采用 GET 变量(它是 FTP 中的文件名)并下载它。但是,它似乎不起作用。运行 echo 语句时,函数本身 (ftp_get) 返回 TRUE,但没有其他任何反应,控制台中也没有错误。

<?php  
$file = $_GET['file'];

$ftp_server = "127.0.0.1";
$ftp_user_name = "user";
$ftp_user_pass = "pass";
// set up a connection or die
$conn_id = ftp_connect($ftp_server) or die("Couldn't connect to $ftp_server"); 

// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

if (ftp_get($conn_id, $file, $file, FTP_BINARY)) {
    echo "Successfully written to $file\n";
} else {
    echo "There was a problem\n";
}

?>

理想情况下,我只需将它们链接到:ftp://example.com/TestFile.txt,它会为他们下载文件,但是,它只会在浏览器中向他们显示文件的内容,而不是下载它。

我已经通过 PHP 手册站点阅读了 FTP 函数,并且我相信 ftp_get 是我想使用的正确的。

是否有更简单的方法可以做到这一点,或者只是我忽略了一些事情?

【问题讨论】:

  • 来自手册:“ftp_get() 从 FTP 服务器检索远程文件,并将其保存到本地文件中。”本地是指运行 PHP 的机器,而不是客户端的桌面机器。不知道有没有比读取保存的文件输出给用户更简单的方法。
  • error_reporting(E_ALL); ini_set('display_errors', '1'); 开启了吗?
  • @Jeffman 没有办法简单地从 FTP 获取文件以下载到用户的 PC 上吗?这似乎不是一个牵强附会的概念。
  • @JohnnyJS 是的,没有错误。它只是将文件写入运行脚本的目录,但我希望最终用户将其下载到他们的 PC 而不是 FTP 的 PC。
  • 你可以试试:echo file_get_contents(ftp_get($conn_id, $file, $file, FTP_BINARY)); 吗?

标签: php javascript html ftp


【解决方案1】:

有两种(或更多)方法可以做到这一点。您可以像使用 ftp_get 一样将文件的副本存储在服务器上,然后将其发送给用户。或者你可以每次都下载。

现在您可以使用 ftp 命令执行此操作,但使用readfile 有一种更快的方法。
按照readfile 文档中的第一个示例:

// Save the file as a url
$file = "ftp://{$ftp_user_name}:{$ftp_user_pass}@{$ftp_server}" . $_GET['file'];

// Set the appropriate headers for a file transfer
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));
// and send them
ob_clean();
flush();

// Send the file
readfile($file);

这将简单地获取文件并将其内容转发给用户。并且标头会使浏览器将文件另存为下载文件。

你可以更进一步。假设您将其保存在一个名为 script.php 的文件中,该文件位于用户可通过http://example.com/ftp/ 访问的目录中。如果您使用的是 apache2 并启用了 mod_rewrite,您可以在此目录中创建一个 .htaccess 文件,其中包含:

RewriteEngine On
RewriteRule ^(.*)$ script.php?file=$1 [L]

当用户导航到http://exmaple.com/ftp/README.md 时,您的script.php 文件将被调用,$_GET['file'] 等于/README.md,来自ftp://user:pass@ftp.example.com/README.md 的文件将下载到他的计算机上。

【讨论】:

    猜你喜欢
    • 2015-03-21
    • 2012-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-02
    • 1970-01-01
    • 2012-04-23
    • 1970-01-01
    相关资源
    最近更新 更多