脚本运行时,无法从FTP服务器自动下载文件


Unable to make a file auto-download from an FTP server when script is run

我正试图编写一个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命令执行此操作,但是有一种使用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的文件将被下载到他的计算机上。