'Function to identify file size

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?



Solution 1:[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! ))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Clipart - Designer