What is the potential issue with using the PHP function filesize() to display file sizes in a download script?
The potential issue with using the PHP function filesize() to display file sizes in a download script is that it returns the file size in bytes, which may not be human-readable. To solve this issue, you can convert the file size to a more readable format, such as KB, MB, or GB, before displaying it to the user.
function formatFileSize($size) {
$units = array('B', 'KB', 'MB', 'GB', 'TB');
$i = 0;
while ($size >= 1024 && $i < 4) {
$size /= 1024;
$i++;
}
return round($size, 2) . ' ' . $units[$i];
}
$fileSize = filesize('example.txt');
$formattedSize = formatFileSize($fileSize);
echo 'File Size: ' . $formattedSize;
Related Questions
- What are some best practices for using preg_replace in PHP to ensure code readability and maintainability?
- What steps should be taken to ensure that PHP modules like mysql.dll and mysqli.dll are properly installed and loaded?
- How can the issue of "Array to string conversion" in line 42 be resolved in the PHP code?