PHP Script to Get Array of FTP Directories and Subdirectories

I was looking through my web host's documentation the other day trying to figure out if there was a way to modify my php.ini file even though I'm on a shared hosting package. I was guessing not, but thought it would be worth looking into. I found good news and bad news – I couldn't actually update the php.ini file, but I could place partial php.ini script in each directory and it would apply the specified changes. I'm trying to disable the on screen error reporting for security reasons. So, yes, it is possible (good news) but I'd have to upload a mini php.ini file into every single directory on my sites (bad news – I have hundreds of folders so that would involve a lot more busy work than I'm interested in.) So, I decided to outsmart the problem...

I created a script using PHP's FTP functions that goes through and uploads the necessary file into each directory. I set up a cronjob that runs this script every week (in case I forget the file when adding new directories, accidentally delete one, etc.) The code that I'm including here is the first part of this file. This code grabs a list of all directories and subdirectories underneath the root FTP directory and stores them in an array ($dir). The $depth variable controls how many levels deep the loop will go through looking for further directories. However, it will stop if it finds that no new directories have been added on any given loop so you can set the depth to an outlandishly high amount if you'd like.


$ftp_user_name = "username" ;
$ftp_user_pass = "password" ;
$ftp_server = "" ;
$depth = 10;

$conn_id = ftp_connect($ftp_server) or (die("Couldn't connect to $ftp_server"));
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
if (!$login_result) { die("Couldn't log in to FTP account."); }

$dir = array(".");
$a = count($dir);
$i = 0;
while (($a != $b) && ($i < $depth)) {
  $a = count($dir) ;
  foreach ($dir as $d) {
    $ftp_dir = $d."/" ;
    $newdir = ftp_nlist($conn_id, $ftp_dir);
    foreach ($newdir as $key => $x) {
      if ((strpos($x,".")) || (strpos($x,".") === 0)) { unset($newdir[$key]); }
      elseif (!in_array($x,$dir)) { $dir[] = $x ; }
  $b = count($dir) ;

print_r($dir) ;



1 Comment

February 1, 2011, 5:52 am
Good Work Buddy.

It would be better if you do the same for cpanel account.

Leave a Comment

Name and email are required. Your email will not be published.

This post was published on December 8th, 2008 by Robert James Reese in the following categories: FTP and PHP. Before using any of the code or other content in this post, you must read and agree to our Terms & Conditions.