Ayan
Ayan

Reputation: 2918

Listing files from a folder give stat error due to filesize

I went through many Q&A but didn't find my solution.

I know there is a function GLOB but I am not using that as I saw somewhere that its not much flexible.

WHAT I AM TRYING TO DO:

I am trying to list files from a folder and show the size of it too.

PROBLEM

It gives me a stat error but the last file's size is being shown.

PHP

<?php
 $thelist = '';
 $count = 0;
 $filelist = array();
 if ($handle = opendir('./storage')) {
   while (false !== ($file = readdir($handle))) {
          if ($file != "." && $file != "..") {
              $filelist[] = $file;
            /*$thelist .= '<li><a href="'.$file.'">'.$file.'</a></li>';*/
            $count = $count+1;
          }
       }
       closedir($handle);
}

for($index=0; $index<$count; $index++){
    $name = $filelist[$index];
    $size = number_format(filesize($filelist[$index]));
    $thelist .= '<li><a href="'.$name.'">'.$name.'</a>'.$size.'</li>';
}
?>

HTML

<div id="list">
    <?php
    if($count<1){
        echo '<div id="empty_storage"><img src="icon.png"><br>Its lonely here!</div>';
    }
    else{
    ?>
        <ul>
        <?php echo $thelist; ?>
        </ul>
    <?php
    }
    ?>
</div>

NOTE

I am trying this on WAMP.

UPDATE

My dump looks like this

array (size=3)
  0 => string 'icon (2).png' (length=12)
  1 => string 'icon.png' (length=8)
  2 => string 'new.png' (length=7)

Upvotes: 1

Views: 173

Answers (1)

yergo
yergo

Reputation: 4990

In my case your error reproduces as:

PHP Warning: filesize(): stat failed for testfile in /home/bnowakowski/storage/test.php on line 18 PHP Stack trace: PHP 1. {main}() /home/bnowakowski/storage/test.php:0 PHP 2. filesize() /home/bnowakowski/storage/test.php:18 PHP Warning: filesize(): stat failed for testdir in /home/bnowakowski/storage/test.php on line 18 PHP Stack trace: PHP 1. {main}() /home/bnowakowski/storage/test.php:0 PHP 2. filesize() /home/bnowakowski/storage/test.php:18

resulting with:

<li><a href="testfile">testfile</a>0</li>
<li><a href="testdir">testdir</a>0</li>

What i had to do to make it working, was to change path of file it was asking for:

$name = $filelist[$index];
$size = number_format(filesize('./storage/' . $name));

to make it asking for size of file in proper location. It works even with symlinks or directories.

Upvotes: 2

Related Questions