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