Solved

FTP Tree Search Algorithm

Posted on 2004-04-07
8
291 Views
Last Modified: 2008-02-01
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
0
Comment
Question by:magneq
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 3
  • 2
8 Comments
 
LVL 1

Expert Comment

by:JDinBRLA
ID: 10781348
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
 
LVL 1

Expert Comment

by:JDinBRLA
ID: 10781362
oops. you can test by running

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

and looking for about 30 functions starting with "ftp_"
0
 
LVL 1

Expert Comment

by:JDinBRLA
ID: 10781412
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
Why Off-Site Backups Are The Only Way To Go

You are probably backing up your data—but how and where? Ransomware is on the rise and there are variants that specifically target backups. Read on to discover why off-site is the way to go.

 

Author Comment

by:magneq
ID: 10781653
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
 
LVL 6

Accepted Solution

by:
CosminB earned 300 total points
ID: 10781973
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
 
LVL 6

Expert Comment

by:CosminB
ID: 10781997
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
 
LVL 6

Expert Comment

by:CosminB
ID: 10782007
... 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
 

Author Comment

by:magneq
ID: 11003179
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

Featured Post

SharePoint Admin?

Enable Your Employees To Focus On The Core With Intuitive Onscreen Guidance That is With You At The Moment of Need.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Generating table dynamically is the most common issue faced by php developers.... So it seems there is a need of an article that explains the basic concept of generating tables dynamically. It just requires a basic knowledge of html and little maths…
Developers of all skill levels should learn to use current best practices when developing websites. However many developers, new and old, fall into the trap of using deprecated features because this is what so many tutorials and books tell them to u…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

729 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question