Simple question (I hope!) I would like to search for files in a local directory (on my server) by partial filename. I'd like the results in an array, the way ftp_nlist does.

In one script I wrote, I use the following:

$contents = ftp_nlist($conn_id, "./MA*.zip");

This gives me an array of files to work with, which I can then manipulate in a "for" clause. Can I do a similar local search by partial filename? Hope this isn't too elementary!

    i found this function in the comments of the manual. its brilliant. works much the same way as the ls command in linux.

    function ls($__dir="./",$__pattern="*.*")
    {
     settype($__dir,"string");
     settype($__pattern,"string");
    
     $__ls=array();
     $__regexp=preg_quote($__pattern,"/");
     $__regexp=preg_replace("/[\\x5C][\x2A]/",".*",$__regexp);
     $__regexp=preg_replace("/[\\x5C][\x3F]/",".", $__regexp);
    
     if(is_dir($__dir))
      if(($__dir_h=@opendir($__dir))!==FALSE)
      {
       while(($__file=readdir($__dir_h))!==FALSE)
       if(preg_match("/^".$__regexp."$/",$__file))
         array_push($__ls,$__file);
    
       closedir($__dir_h);
       sort($__ls,SORT_STRING);
      }
    
     return $__ls;
    }
    

    usage;

    echo ls('/home','*.zip');

    this should output all .zip files in your /home directory.

      Thorpe,

      Thanks for your reply! I tried it, but no results. I experimented and added an echo statement at the end of the "if" statements and it's not showing up.

      It looks to me like there are missing {} brackest with some of the if statements. Are they ok, or is that part of it?

      Thanks again.

        I can't get it to work, either.

        The "missing" brackets seem to be optional ones.

          Couldn't a regular pull with a pattern check work? Something as simple as .zip wouldn't even require regex.

          <?php
          $dir  = '/path/to/folder/'; #Make sure there's the trailing /
          $look = '.zip';
          $res  = get_list($dir, $look);
          if(is_array($res))
             print_r($res);
          else
             echo $res;
          
          function get_list($directory, $pattern) {
             $results = array();
             if($open = opendir($directory)) {
                while(false !== ($file = readdir($open))) {
                   if(strpos($file, $pattern) !== false)
                      $results[] = $directory.$file;
                }
                closedir($open);
                return $results;
             }
             return 'Could not open directory '.$directory;
          }
          ?>
          

          Not tested, completely unsophisticated, but should shoot you a step into the direction you want to go I'd think.

            If anyone's interested, here's a version that will work on both Windows (not in safe mode) and Linux:

            function ls_sortof($dir = '', $pattern = '') 
            {
                if (($dir != '') && (substr($dir, -1) != '/')) {
                    $dir .= '/';
                }
            
            if (strpos($_SERVER['SERVER_SOFTWARE'], 'Win') !== false) {
                $dir = str_replace('/', '\\\\', $dir); // Double the backslash
                $par = $dir . $pattern . ' /B';
                $ls = `dir $par`;
            } else {
                ob_start();
                passthru('ls ' . $dir . $pattern);
                $ls = ob_get_contents();
                ob_end_clean();
            }
            
            $ls_arr = explode("\n", $ls);
            foreach ($ls_arr as $key => $value) {
                $ls_arr[$key] = basename(trim($value));
                if (empty($ls_arr[$key])) {
                    unset($ls_arr[$key]);
                }
            }
            
            if (!$ls_arr) {
                return false;
            } else {
                return $ls_arr;
            }
            }

            Usage:

            $files = ls_sortof('.', '*.zip');
            if ($files) {
                foreach ($files as $each_file) {
                    echo $each_file . '<br />';
                }
            } else {
                echo 'No files found';
            }

            Edit: Double backslash line:
            $dir = str_replace('/', '\\', $dir);

              Installer,

              I'm getting the following error:

              Parse error: parse error, unexpected T_CONSTANT_ENCAPSED_STRING

              It's related to this line:

                      passthru('ls ' . $dir . $pattern);

              Any ideas?

                That's the same error I get if I don't double the backslash on the line where it says "// Double the backslash". So...double the backslash. 🙂

                The line should look like this:

                $dir = str_replace('/', '\\', $dir); 

                  You're awesome!

                  I saw that, but thought to myself that it would have been easier to just put in a double backslash than adding a comment to say to do it. Sometimes it really means what it says.

                  Thanks and sorry for not taking it as literally as I should have!

                    It's the way it is because of the forum software. There's probably an easy way to get it to show correctly, but I haven't stumbled onto it yet.

                      BTW, (and I promise to quit posting long code to this thread), here's a slightly improved (imo) version that will let you retrieve the file listing either with or without the path string prepended to the file name:

                      function ls_sortof($dir = '', $pattern = '', $with_path = true) 
                      {
                          if (($dir != '') && (substr($dir, -1) != '/')) {
                              $dir .= '/';
                          }
                      
                      if (strpos($_SERVER['SERVER_SOFTWARE'], 'Win') !== false) {
                          $dir = str_replace('/', '\\', $dir);  // Don't forget :-)
                          $par = $dir . $pattern . ' /B';
                          $ls = `dir $par`;
                      } else {
                          ob_start();
                          passthru('ls ' . $dir . $pattern);
                          $ls = ob_get_contents();
                          ob_end_clean();
                      }
                      
                      $ls_arr = explode("\n", $ls);
                      foreach ($ls_arr as $key => $value) {
                          if ($with_path) {
                              $ls_arr[$key] = $dir . basename(trim($value));
                          } else {
                              $ls_arr[$key] = basename(trim($value));
                          }
                          if (empty($value)) {
                              unset($ls_arr[$key]);
                          }
                      }
                      
                      if (!$ls_arr) {
                          return false;
                      } else {
                          return $ls_arr;
                      }
                      }
                        Write a Reply...