1

我正在尝试编写一个 PHP 页面,该页面采用 GET 变量(它是 FTP 中的文件名)并下载它。但是,它似乎不起作用。函数本身 (ftp_get) 在运行 echo 语句时返回 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 是我想使用的正确的。

是否有可能更简单的方法来做到这一点,或者它只是我忽略的东西?

4

1 回答 1

2

有两种(或更多)方法可以做到这一点。您可以像使用 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']equal to/README.md并将文件ftp://user:pass@ftp.example.com/README.md下载他的计算机上。

于 2013-08-07T17:17:08.353 回答