FTP Tree Search Algorithm

Hello all,

Currently in a deep fix and need help from anyone.

Need to search for a file on a server using FTP connection under PHP language. Currently can't figure out how to write the algorithm.

1) File location and node level is not known
2) While will be a ".zip" format
3) Given is only one of the directory name the file in under.

I have never written a search before but I think the search need to be recursive yet I don't know how to backtrack. Please provide me with a sample of the algorithm that I can learn.

Thanks in advance.

magneq
magneqAsked:
Who is Participating?

[Webinar] Streamline your web hosting managementRegister Today

x
 
CosminBConnect With a Mentor Commented:
try this one:

<?php
set_time_limit(0);
$ftpServer = 'server';
$ftpUser = 'username';
$ftpPassword = 'password';
$searchedFile = 'somefile.zip';
$conn = ftp_connect($ftpServer) or die('Could not connect to the ftp server');
ftp_login($conn, $ftpUser, $ftpPassword) or die('Could not login to the ftp server');
$pwd = ftp_pwd($conn);
echo 'Initial directory: ',$pwd,"<br>\n";
if (findFile($pwd, $searchedFile))
{
      echo "\n\n<br>The file ",$searchedFile,' has been found in ',$foundIn;
}
else
{
      echo "\n\n<br>The file wasn\'t found";
}

function findFile($initialDirectory, $fileName)
{
      global $conn, $foundIn;
      $dirContents = ftp_rawlist($conn, $initialDirectory);
      $dirCount = count($dirContents);
      for ($i=0; $i<$dirCount; $i++)
      {
            $item = parseLine($dirContents[$i]);
            if ($item['type'] == 'file')
            {
                  if ($item['name'] == $fileName)
                  {
                        $foundIn = $initialDirectory;
                        return true;
                  }
            }
            else
            {
                  $subDirs[] = $item;
            }
      }
      //process the subdirectories
      for ($i=0; $i<count($subDirs); $i++)
      {
            if (findFile($initialDirectory.'/' .$subDirs[$i]['name'], $fileName))
            {
                  return true;
                  break;
            }
      }
      return false;
}

function parseLine(&$line)
{
      sscanf($line , '%s %d %d %d %d %s %s %s %s', &$item['rights'], &$item['count'], &$item['UID'], &$item['GID'], &$item['size'], &$item['month'], &$item['year'], &$item['time'], &$item['name']);
      if (strpos($line, $item['name'])+strlen($item['name']) != strlen($line))
      {
            $item['name'] = substr($line, strpos($line, $item['name']));
      }
      $item['type'] = ($item['count'] != 1) ? 'dir' : 'file';
      return $item;
}
ftp_close($conn);
?>
0
 
JDinBRLACommented:
I'll work on this for you. first of all, do you have the FTP functions built-in? (automatically built-in with windows, requires --enable-ftp option on unix)
0
 
JDinBRLACommented:
oops. you can test by running

$funcs = get_defined_functions();
var_dump($funcs)

and looking for about 30 functions starting with "ftp_"
0
Get your problem seen by more experts

Be seen. Boost your question’s priority for more expert views and faster solutions

 
JDinBRLACommented:
well you know what? While I was building a sample set of code, I ran across this in the user notes of the php docs:

An example script for rekursiv directory analysis ... interesting are the ereg functions for spliting the content based on the system type...
(http://beben.lanparty.de/smint/ftp_rekdiranalys.phps)
function analysedir($dirline)
{
   global $systyp,$ftp_server,$stop;
   
   if(ereg("([-dl])[rwxst-]{9}",substr($dirline,0,10))) {
       $systyp = "UNIX";
   }
   
   if(substr($dirline,0,5) == "total") {
       $dirinfo[0] = -1;
   } elseif($systyp=="Windows_NT") {
       if(ereg("[-0-9]+ *[0-9:]+[PA]?M? +<DIR> {10}(.*)",$dirline,$regs)) {
           $dirinfo[0] = 1;
           $dirinfo[1] = 0;
           $dirinfo[2] = $regs[1];
       } elseif(ereg("[-0-9]+ *[0-9:]+[PA]?M? +([0-9]+) (.*)",$dirline,$regs)) {
           $dirinfo[0] = 0;
           $dirinfo[1] = $regs[1];
           $dirinfo[2] = $regs[2];
       }
   } elseif($systyp=="UNIX") {
       if(ereg("([-d])[rwxst-]{9}.* ([0-9]*) [a-zA-Z]+ [0-9: ]*[0-9] (.+)",$dirline,$regs)) {
           if($regs[1]=="d")    $dirinfo[0] = 1;
           $dirinfo[1] = $regs[2];
           $dirinfo[2] = $regs[3];
       }
   }
   
   if(($dirinfo[2]==".")||($dirinfo[2]=="..")) $dirinfo[0]=0;
   // array -> 0 = switch, directory or not
   // array -> 1 = filesize (if dir =0)
   // array -> 2 = filename or dirname
       
   return $dirinfo;
}
function rekdir($dir)
{
   global $conn_id,$filetyps,$exectyps,$ftp_server,$banlist,$size,$ssize;
   echo "<b>$dir</b>
";
   
   $dirlist = ftp_rawlist($conn_id,"");
   for($i=0;$i<count($dirlist);$i++) {
       $dirinfo = analysedir($dirlist[$i]);
   
       if($dirinfo[0]==1) {
           $newdir = "$dir/$dirinfo[2]";
           
           if(($dirinfo[2]=="~")||(substr($dirinfo[2],0,1)==" "))
               $chdir=ftp_chdir($conn_id,$newdir);
           else    $chdir=ftp_chdir($conn_id,$dirinfo[2]);
           
           $stop = 0;
//            for($k=0;($k<count($banlist))&&(!$stop);$k++) {
//                if(strpos($newdir,$banlist[$k])!=0) $stop=1;
//            }
           
           if(!$stop && $chdir) {
               rekdir($newdir);
           }
       
           if(!ftp_chdir($conn_id,$dir))    ftp_cdup($conn_id);
       } elseif($dirinfo[0]==0) {
           echo "$dirinfo[2]
";
           
           $size += $dirinfo[1];
       }
   }
   
}
$conn_id = ftp_connect($ftp_server);
$login_result = @ftp_login($conn_id, $user, $password);
if ($login_result) {
   $real_systyp = ftp_systype($conn_id);
   $systyp = $real_systyp;
   echo "scanning... $systyp
";
   rekdir("");
   ftp_quit($conn_id);
}
0
 
magneqAuthor Commented:
Thanks for reply, JDinBRLA.

I have the built in FTP functions. Just can't figure out how to write the code.
Now have to take a bit of time to digest the code you provide... hold on eh.

0
 
CosminBCommented:
it searches for a file name in your home ftp directory. It can search in any directory you want if you replace
 $pwd = ftp_pwd($conn);
   with
 $pwd = '/your/search/dir'; //remember that this dir has to be accesible by ftp

The script stops when it finds the first file but it can be modified to find all occurences of that given file. Also the script only searches for files(file names) but if can be modified to search for directories or files with a specific extension.

If you have any questions feel free to ask them
0
 
CosminBCommented:
... i forgot to mention  that i only tested on a linux machine, and the ftp server was also kon a linux machine but i guess it will work on windows too
0
 
magneqAuthor Commented:
Hello CosminB,

Thanks for the code. Though not a direct solution but it does serve me as a very useful reference.
Thanks a lot man, and apologize for being late in replying. Had already come out with another code from what you had given me.


Best Regards,

magneq
0
All Courses

From novice to tech pro — start learning today.