morrisonlevi

Open all files in a directory and read a line.

Aug 24th, 2011
178
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.54 KB | None | 0 0
  1. <?php
  2.  
  3.     function readLine($lineNumber, $fileName) {
  4.         /**
  5.          * @param int $lineNumber The line number you want to read from the file.
  6.          * @param string $fileName The string representing the file you wish to open.
  7.          *
  8.          * @return string The contents of the line in the file.
  9.          */
  10.         $file = file($fileName);
  11.         return $file[$lineNumber-1];
  12.     }
  13.     function readLineFrom($lineNumber, $fileNames) {
  14.         /**
  15.          * @param int $lineNumber The line number you want to read from the file.
  16.          * @param string|array $files Either a string for the file you want to open, or an array of filenames.
  17.          *
  18.          * @return array An associative array of the filename to the contents of the line.
  19.          */
  20.         $lines = array();
  21.         if(is_array($fileNames)) {
  22.             foreach($fileNames as $fileName) {
  23.                 $lines[$fileName] = readLine($lineNumber,$fileName);
  24.             }
  25.         } else {
  26.             $lines[$fileNames] = readLine($fileNames);
  27.         }
  28.        
  29.         return $lines;
  30.     }
  31.    
  32.     function getFileNamesFromDirectory($directory = '.') {
  33.         /**
  34.          * @param string $directory The path to directory you'd like to get filenames from. Defaults to current directory.
  35.          *
  36.          * @return array An array of filenames.  Empty if there are no files.
  37.          */
  38.         $fileNames = array();
  39.         if ($handle = opendir($directory)) {
  40.             while (false !== ($file = readdir($handle))) {
  41.                 if ($file != "." && $file != "..") {
  42.                     $fileNames[] = $file;
  43.                 }
  44.             }
  45.             closedir($handle);
  46.         }
  47.         return $fileNames;
  48.     }
  49.     echo "<pre>";
  50.     print_r(
  51.         readLineFrom(5, getFileNamesFromDirectory('/var/www/'))
  52.     );
  53.     echo "</pre>";
  54. ?>
Advertisement
Add Comment
Please, Sign In to add comment