Solved

FTP Tree Search Algorithm

Posted on 2004-04-07
8
279 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
  • 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
 

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
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
how to create a scatter graph with straight lines 6 29
simplest php form 3 64
Is this error or Notice in php error log? 6 32
.htaccess 5 22
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…
Part of the Global Positioning System A geocode (https://developers.google.com/maps/documentation/geocoding/) is the major subset of a GPS coordinate (http://en.wikipedia.org/wiki/Global_Positioning_System), the other parts being the altitude and t…
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

867 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

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now