2

I've been searching for hours and tried tons of combinations, but have thus far been unsuccessful in my attempts. I have a folder on a remote FTP server whose contents I wish to display as links on a webpage. Upon clicking the link, I want it to download that specific file to the user's computer. I've spent hours trying jQuery/ajax combos with php and html mixed in. Any help would be much appreciated!

<?php
    $ftp_server = "host info here";
    $ftp_user = "user info here";
    $ftp_pass = "pw here";

    // set up a connection or die
    $conn_id2 = ftp_connect($ftp_server) or die("Couldn't connect to $ftp_server"); 
    // try to login
    ftp_login($conn_id2, $ftp_user, $ftp_pass);
    ftp_pasv($conn_id2, true);

    $filelist = ftp_nlist($conn_id2, "/folder/path/here");
    foreach ($filelist as $file)
    {
        echo $file;
        echo "<br />";
    }
    ftp_close($conn_id2);
?>

That is the code before trying to link the files for download. This successfully lists all the files in the folder. I do not want to download all of the files to the local server every time the page loads, since they are large files and there's a lot of them. I would like only to download them upon request via clicking the filename.

The overall idea of what I'm attempting is to pass the link text to a function which would open the FTP connection again and download the specified file. It would be awesome to download a copy directly to the client's computer upon clicking the link, but if I need to download to the local server first, that is an option, then I'll just clear it on page load.

What I've tried: I've spent hours google-ing jQuery/ajax scripts, tried functions in separate files and passing parameters to them, and more. Thus far, nothing has worked. While I'm experienced in several coding languages, I'm newer to php/js, so any help is much appreciated!

Thanks in advance for your time.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
dboatman_z
  • 61
  • 1
  • 8

1 Answers1

1

I know this is an old thread, but I recently had to do the same thing.

Solution:

$url = "ftp://ftp.bla.com";
// connect and login to FTP server
$ftp = ftp_connect("ftp.bla.com");
if (!$ftp) die('could not connect.');

// login
$login = ftp_login($ftp, "anonymous", "");
if (!$login) die('could not login.');

// enter passive mode
$passsive = ftp_pasv($ftp, true);
if (!$passsive ) die('could not enable passive mode.');

// get listing
$listing = ftp_nlist($ftp, "/path/to/dir");

foreach($listing as $value){
    echo "<a href='$url$value'>", substr($value, strrpos($value, '\\') + 1) ,"</a><br>";
}

This will display the file names as a link, if you click on them, they will be downloaded individually.

**Note: the files in my ftp did not have spaces in their names!

Resources:

Community
  • 1
  • 1
avn
  • 822
  • 1
  • 14
  • 31