Search code examples
phpforeachglobfilesize

PHP filesize for files in directory not shown


I would like to display the filesize for every file in a directory in a table. But the size of the files can´t be shown.

This is the code I use:

$dir    = 'audio';

$files = array_slice(scandir('audio'), 2);
sort($files, SORT_NATURAL | SORT_FLAG_CASE);

$size = (glob("audio/*.mp3"));
        
echo "<table border><tr><th>Dateiname</th><th>Dateingröße</th></tr>";
    foreach ($files as $file) {
        echo 
        "<tr>
            <td>
                <a href='audio/" . $file . "'target='_blank'>" . $file . "</a>
            </td>
            <td>" . filesize($size) . " Byte
            </td>
        </tr>";
    }
echo "</table>";

Can someone tell me how to fix this, so the size is shown in the second table column?


Solution

  • You seem to be a bit confused about what each function actually does and returns.

    Here is a working version of the code, I removed some parts as they were kind of doing the same thing. And while you were looping through an array $files, you were using another array $size inside your loop within a function that accepts only a string filesize().

    <?php
    
    $files = (glob("audio/*.mp3"));
    sort($files, SORT_NATURAL | SORT_FLAG_CASE);
    
    echo "<table border><tr><th>Dateiname</th><th>Dateingröße</th></tr>";
    foreach ($files as $file) {
        echo
            "<tr>
                <td>
                    <a href='".$file."'target='_blank'>".basename($file)."</a>
                </td>
                <td>".filesize($file)." Byte
                </td>
            </tr>";
    }
    echo "</table>";