php查找文件大小的原理是遍历目录然后再利用filesize来计算文件大小,然后我们再加一判断就可以了,下面整理了一些例子。
我们先来看遍历目录
<?php
function tree($directory) {
$mydir = dir($directory);
echo "<ul>n";
while ($file = $mydir->read()) {
if ((is_dir("$directory/$file")) AND ($file != ".") AND ($file != "..")) {
echo "<li><font color="
//ff00cc"><b>$file</b></font></li>n";
tree("$directory/$file");
} else echo "<li>$file</li>n";
}
echo "</ul>n";
$mydir->close();
}
//开始运行
echo "<h2>目录为粉红色</h2><br>n";
tree("./phprm");
?>这样只是把所有目录下的文件显示了,但我们要判断大小需加上round(filesize($cpath)/1024,1)函数了,这样我们获取大小之后就可以显示文件大小了。
<?php
header("Content-Type:text/html;charset=gbk");
set_time_limit(0);
$dirpath = dirname(__FILE__);
//bytes
$limitByte = 1024 * 110;
//这里改成你合适的查找文件最低大小,单位为字节。1024*100表示 1024*100字节,即100KB
$arrRes = $arrTmp = array();
showMaxFile($dirpath, $limitByte);
function showMaxFile($path, $limitByte) {
global $arrRes;
$h = opendir($path);
if ($h) {
while (false !== ($file = readdir($h))) {
if ($file != '.' && $file != '..') {
$cpath = $path . '/' . $file;
if (is_dir($cpath)) {
showMaxFile($cpath, $limitByte);
} else {
if (filesize($cpath) > $limitByte) {
$arrRes[] = array(
$cpath,
round(filesize($cpath) / 1024, 1)
);
//echo "<p>{$cpath}<br />".(filesize($cpath) / 1024)."KB</p>";
}
}
}
}
}
closedir($h);
}
foreach ($arrRes as $k => $v) {
$arrTmp[$k] = $v[1];
}
arsort($arrTmp);
foreach ($arrTmp as $k => $v) {
echo "<p>" . str_replace($dirpath, '', $arrRes[$k][0]) . "<br />" . $arrRes[$k][1] . "</p>
<div class="aritcle_card">
<a class="aritcle_card_img" href="/xiazai/code/10638">
<img src="https://img.php.cn/upload/webcode/000/000/005/176309820356916.png" alt="ECTouch移动商城系统">
</a>
<div class="aritcle_card_info">
<a href="/xiazai/code/10638">ECTouch移动商城系统</a>
<p>ECTouch是上海商创网络科技有限公司推出的一套基于 PHP 和 MySQL 数据库构建的开源且易于使用的移动商城网店系统!应用于各种服务器平台的高效、快速和易于管理的网店解决方案,采用稳定的MVC框架开发,完美对接ecshop系统与模板堂众多模板,为中小企业提供最佳的移动电商解决方案。ECTouch程序源代码完全无加密。安装时只需将已集成的文件夹放进指定位置,通过浏览器访问一键安装,无需对已有</p>
<div class="">
<img src="/static/images/card_xiazai.png" alt="ECTouch移动商城系统">
<span>0</span>
</div>
</div>
<a href="/xiazai/code/10638" class="aritcle_card_btn">
<span>查看详情</span>
<img src="/static/images/cardxiayige-3.png" alt="ECTouch移动商城系统">
</a>
</div>
<p><span>立即学习</span>“<a href="https://pan.quark.cn/s/7fc7563c4182" style="text-decoration: underline !important; color: blue; font-weight: bolder;" rel="nofollow" target="_blank">PHP免费学习笔记(深入)</a>”;</p>";
}
?>最后给大家附一个字节计算函数,这个可以转换
<?php
//字节数转换成带单位的
/* 原理是利用对数求出欲转换的字节数是1024的几次方。
* 其实就是利用对数的特性确定单位。
*/
function size2mb($size, $digits = 2) { //digits,要保留几位小数
$unit = array(
'',
'K',
'M',
'G',
'T',
'P'
); //单位数组,是必须1024进制依次的哦。
$base = 1024; //对数的基数
$i = floor(log($size, $base)); //字节数对1024取对数,值向下取整。
return round($size / pow($base, $i) , $digits) . ' ' . $unit[$i] . 'B';
}
?>
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号