Skip to content
Advertisement

List and download clicked file from FTP

I have FTP and I need list all files in FTP in uploads directory and after click on any listed file it will download the specific file from FTP.

It list my files in uploads directory but when I will try to download file so it types me “no file”

My code:

    // connect and login to FTP server
$ftp_server = "IP";
$ftp_conn = ftp_connect($ftp_server) or die("Could not connect to $ftp_server");
$login = ftp_login($ftp_conn, "name", "password");

// list all files in upload directory and with "a" download file from FTP
$target_dir = "uploads/";
$files = ftp_nlist($ftp_conn, $target_dir);
foreach($files as $file) {
    echo "<a href='$file' download>$file</a>";
    echo "<br>";
}

Advertisement

Answer

Your link in the generated <a> tag points back to the web server, which does not contain the linked file.

What you need to do is to link to a PHP script, giving it a name of the file to download. The script will then download the file from an FTP server and pass the downloaded file back to the user (to the webbrowser).

echo "<a href="download.php?file=".urlencode($file)."">".htmlspecialchars($file)."</a>";

A very trivial version of the download.php script:

<?

header('Content-Type: application/octet-stream');

echo file_get_contents('ftp://username:password@ftp.example.com/path/' . $_GET["file"]);

The download.php script uses FTP URL wrappers. If that’s not allowed on your web server, you have to go the harder way with FTP functions. See PHP: How do I read a file from FTP server into a variable?


Though for a really correct solution, you should provide some HTTP headers related to the file, like Content-Length, Content-Type and Content-Disposition.

Also the above trivial example will first download whole file from the FTP server to the webserver. And only then it will start streaming it to the user (webbrowser). What is a waste of time and also of a memory on the webserver.

For a better solution, see Download file via PHP script from FTP server to browser with Content-Length header without storing the file on the web server.

You may also want to autodetect Content-Type, unless all your files are of the same type.


A related question about implementing an FTP upload with a webpage:
Displaying recently uploaded images from remote FTP server in PHP

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement