user61026
user61026

Reputation: 295

PHP absolute file

How do we return the absolute path of largest file in a particular directory?

I've been fishing around and haven't turned up anything concrete?

I'm thinking it has something to do with glob()?

Upvotes: 0

Views: 62

Answers (3)

meda
meda

Reputation: 45490

function getFileSize($directory) {
    $files = array();
    foreach (glob($directory. '*.*') as $file) {
        $files[] = array('path' => $file, 'size' => filesize($file));
    }
    return $files;
}

function getMaxFile($files) {
    $maxSize = 0;
    $maxIndex = -1;
    for ($i = 0; $i < count($files); $i++) {
        if ($files[$i]['size'] > $maxSize) {
            $maxSize = max($maxSize, $files[$i]['size']);
            $maxIndex = $i;
        }
    }
    return $maxIndex;
}

usage:

$dir = '/some/path';
$files = getFileSize($dir);
echo '<pre>';
print_r($files);
echo '</pre>';

$maxIndex = getMaxFile($files);
var_dump($files[$maxIndex]);

Upvotes: 0

voodoo417
voodoo417

Reputation: 12101

$dir = 'DIR_NAME';
$max_filesize = 0;
$path= '';

foreach(new RecursiveIteratorIterator(new RecursiveDirectoryIterator(realpath($dir),FilesystemIterator::SKIP_DOTS)) as $file){
     if ($file->getSize() >= $max_filesize){
       $max_filesize = $file->getSize();
       $path = $file->getRealPath(); // get absolute path            
     }
}   
echo $path;

Upvotes: 1

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

$sz = 0;
$dir = '/tmp'; // will find largest for `/tmp`
if ($handle = opendir($dir)) { // will iterate through $dir
  while (false !== ($entry = readdir($handle))) {
    if(($curr = filesize($dir . '/' . $entry)) > $sz) { // found larger!
      $sz = $curr;
      $name = $entry;
    }
  }
}
echo $dir . '/' . $name; // largest

Upvotes: 1

Related Questions