识别文件大小的函数
我正在使用以下代码来获取文件大小。文件托管在我的服务器上。
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"; } }
当我将文件路径作为字符串放置时,该函数可以工作并提供文件大小:
echo 'This file is ' . getFilesize($_SERVER['DOCUMENT_ROOT'] . '/images/vector_files/flower.pdf'); // OUTPUT: This file is 15 KB
当我通过变量放置相同的文件路径时,该函数将不起作用。
$link_trimmed = '/images/vector_files/flower.pdf'; $file = $_SERVER['DOCUMENT_ROOT']. $link_trimmed; echo 'This file is ' . getFilesize($file); // OUTPUT: File does not exist
请帮帮我,出了什么问题?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
感谢您的回答。经过详细的代码审查后,我指出问题是变量 $link_trimmed 末尾的空格(路径类似于“/images/vector_files/flower.pdf_”。原因是使用函数 str_replace( 进行预先准备) )。所以,我解决了这个问题并且功能运行得很好!))
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! ))