Forum Moderators: coopster

Message Too Old, No Replies

Scanning FTP folders and files

         

ahmed24

9:39 pm on Dec 12, 2014 (gmt 0)

10+ Year Member



I have the following PHP code that scans a folder called files and returns a JSON result for a JQuery file viewer. Problem is that my files are on a remote FTP server. Can anyone suggest how this code can be adapted to perform the same function but on an FTP server instead?

Thanks.



$dir = "files";

// Run the recursive function

$response = scan($dir);


// This function scans the files folder recursively, and builds a large array

function scan($dir){

$files = array();

// Is there actually such a folder/file?

if(file_exists($dir)){

foreach(scandir($dir) as $f) {

if(!$f || $f[0] == '.') {
continue; // Ignore hidden files
}

if(is_dir($dir . '/' . $f)) {

// The path is a folder

$files[] = array(
"name" => $f,
"type" => "folder",
"path" => $dir . '/' . $f,
"items" => scan($dir . '/' . $f) // Recursively get the contents of the folder
);
}

else {

// It is a file

$files[] = array(
"name" => $f,
"type" => "file",
"path" => $dir . '/' . $f,
"size" => filesize($dir . '/' . $f) // Gets the size of this file
);
}
}

}

return $files;
}



// Output the directory listing as JSON

header('Content-type: application/json');

echo json_encode(array(
"name" => "files",
"type" => "folder",
"path" => $dir,
"items" => $response
));

brotherhood of LAN

9:49 pm on Dec 12, 2014 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



There is a handy suite of FTP functions available in PHP. [php.net...]

You'd maybe want to have an interface and two classes, one dealing with a local filesystem and another that has an FTP wrapper/functions to deal with remote ones. There's a number of examples in the PHP manual to get you started... I'd suggest testing your FTP functionality as a standalone thing before merging it with your existing code.

One caveat to point out is to watch the timeouts of your jquery requests and ensure they're longer than any FTP timeouts you have.