1

I am using the following code to get file size. Files are hosted on my server.


function getFilesize($file)
{
    if(!file_exists($file)) return "File does not exist";

    $filesize = filesize($file);

    if($filesize > 1024)
    {
        $filesize = ($filesize/1024);

        if($filesize > 1024)
        {
            $filesize = ($filesize/1024);

            if($filesize > 1024)
            {
                $filesize = ($filesize/1024);
                $filesize = round($filesize, 1);
                return $filesize." GB";
            }
            else
            {
                $filesize = round($filesize, 1);
                return $filesize." MB";
            }
        }
        else
        {
            $filesize = round($filesize, 1);
            return $filesize." KB";
        }
    }
    else
    {
        $filesize = round($filesize, 1);
        return $filesize." Bytes";
    }
}

In the case when I put a file path as a string, the function works and delivers a file size:

echo 'This file is ' . getFilesize($_SERVER['DOCUMENT_ROOT'] . '/images/vector_files/flower.pdf');

// OUTPUT: This file is 15 KB

In the case when I put the same file path via variable, the function does not work.

$link_trimmed = '/images/vector_files/flower.pdf';

$file = $_SERVER['DOCUMENT_ROOT']. $link_trimmed;

echo 'This file is ' . getFilesize($file);

// OUTPUT: File does not exist

Please help me, what is wrong?

  • I don't see anything. Why don't you echo the filename inside your function? They should echo the same thing. – KIKO Software Mar 14 '22 at 20:05
  • Does this answer your question? [human readable file size](https://stackoverflow.com/questions/15188033/human-readable-file-size) – Ron van der Heijden Mar 14 '22 at 20:07
  • The output should be the same assuming nothing else changed. However if you are e.g. including this file from a different file then `DOCUMENT_ROOT` might be different. Do a `var_dump($_SERVER['DOCUMENT_ROOT'])` to confirm – apokryfos Mar 14 '22 at 20:07

1 Answers1

1

thanks for your answers. After detailed code review I indicated that the problem was a white space at the end of the variable $link_trimmed (path was like '/images/vector_files/flower.pdf_'. Reason for is is preparation in upfront by use of the function str_replace(). So, I fixed this issue and function works very well! ))

  • If this fixed your issue, consider marking it as the accepted answer: https://stackoverflow.com/help/accepted-answer – voxobscuro Mar 14 '22 at 22:23