Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the list of files over FTP

Tags:

php

ftp

I want to print the list of files and only files from an FTP server, here is what I could accomplish.

<?php
    $ftp_server = "my ftp server";
    $conn_id = ftp_connect($ftp_server);
    $ftp_user_name = "ftp username";
    $ftp_user_pass = "ftp password";
    $login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
    $contents = ftp_nlist($conn_id, '/');
    for ($i = 0 ; $i < count($contents) ; $i++)
        echo "<li>" . substr($contents[$i],1) . "</li>";
    ftp_close($conn_id);
?>

but this prints the names of files and folders. How can I just print the names of files (files may not have extensions!)

like image 926
sikas Avatar asked Nov 03 '10 15:11

sikas


2 Answers

Here is a script that will do it for you, courtesy of a poster on ftp_nlist (PHP Docs):

<?php

//identify directories

function ftp_is_dir($dir) {
  global $ftp_connect;
  if (@ftp_chdir($ftp_connect, $dir)) {
       ftp_chdir($ftp_connect, '..');
       return true;
  } else {
       return false;
  }
}
$ftp_nlist = ftp_nlist($ftp_connect, ".");

//alphabetical sorting

sort($ftp_nlist);
foreach ($ftp_nlist as $v) {

//1. ftp_is_dir() is true => directory
  if (ftp_is_dir($v)) {

//output as [ directory ]
      echo "[ " . $v . " ]<br />\n";
  }
}
foreach ($ftp_nlist as $v) {

//2. ftp_is_dir() is false => file
  if (!ftp_is_dir($v)) {

//output as file
      echo "" . $v . "<br />\n";
  }
}
?>
like image 92
Justin Ethier Avatar answered Oct 19 '22 07:10

Justin Ethier


Options:

1) you can use ftp_rawlist instead of ftp_nlist to get the full listing for the file/directory, which should indicate whether it's a directory. However, the format of that listing will depend on the operating system of the ftp server. For example, on a unix/linux system the raw listing might look something like this:

drwxrwxr-x  3 jm72 jm72  4096 Nov  2 16:39 myDir
-rw-rw-r--  1 jm72 jm72   257 Nov  2 16:39 myFile

where the "d" in the first column will tell you it's a directory. Not sure what it would look like on a Windows server.

2) for each file name you return, try to CD into it. If you can, it's a directory!

if (ftp_chdir($conn_id, substr($contents[$i],1)) {
  //it's a directory, don't include it in your list
  ftp_cdup($conn_id) //don't forget to go back up to the directory you started in!
}
like image 31
Jacob Mattison Avatar answered Oct 19 '22 07:10

Jacob Mattison