Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

filesize(): stat failed for specific path - php

Tags:

php

filesize

stat

i am coding a simple doc managing script and need to get the file size and file type /file or folder/ in a table. somehow it doesn't work into the mention directory. please help if possible:

    <?php
$path = "./documents";
$dh = dir($path);
while( ($file=$dh->read()) ) 
{
    if( $file=="." || $file=="..")continue;
    echo "<tr><td><a href='download.php?f=$file' title='Click to Open/Download'>$file</a></td>";
    echo "<td>";
    echo (is_file($file))? "<img src='file.jpg'/> FILE" : "<img src='folder.jpg'/> FOLDER ";
    echo "</td><td>" .filesize($file)."</td>";
    echo "<td><input type='checkbox' name='delete[]'/></td></tr>";
}
?>

it does actually has 2 errors - one the file size doesn't work for the location, if i change it to path to "." - everything is ok, but if i try to change to the folder where i need it /documents ...all goes bad, and secondly - it doesn't take the right icon file as well, same type of problem. thank you

like image 426
Ivan M Avatar asked Dec 27 '15 15:12

Ivan M


People also ask

Why is filesize() not working in /tmp?

/tmp is not writable by PHP - then filesize () is not allowed there … apparently. Try moving the file to the dir you want it (move_uploaded_file) and do a filesize () there to test.

How do I use filesize with relative path names?

Under Windows 10 filesize obviously cannot work with relative path names. Use absolute path instead. $size = filesize (".\myfile.txt"); does not work for me while "d:\MyFiles\Myfile.txt" will do. The same applys to similar functions like is_file () or stat (). They won't work correctly unless given an absolute path.

What happens when a PHP file size is larger than 2GB?

Note: Because PHP's integer type is signed and many platforms use 32bit integers, some filesystem functions may return unexpected results for files which are larger than 2GB. Upon failure, an E_WARNING is emitted. Note: The results of this function are cached. See clearstatcache () for more details.


1 Answers

Problem is, $file is only the filename without the directory prefix, so checking on it won't work. One way would be to have a variable with the absolute filename (say $realfile). You'd then have to alter your code and use this variable for the file checks:

<?php
$path = "./documents";
$dh = dir($path);
while(($file=$dh->read()) !== false) {
    if( $file=="." || $file=="..") continue;
    // have a new variable for the real filepath
    $realfile = $path . "/" . $file;
    echo "<tr><td><a href='download.php?f=$file' title='Click to Open/Download'>$file</a></td>";
    echo "<td>";
    echo (is_file($realfile))? "<img src='file.jpg'/> FILE" : "<img src='folder.jpg'/> FOLDER ";
    echo "</td><td>" .filesize($realfile)."</td>";
    echo "<td><input type='checkbox' name='delete[]'/></td></tr>";
}
?>
like image 171
Jan Avatar answered Sep 30 '22 15:09

Jan