php获取某个目录大小的代码

yipeiwu_com6年前PHP代码库
大致程序思想就是使用递规来计算目录占用空间多少, 然后再把这个占用空间的值写进文本文件里, 那么只要访问这个txt文件就知道占用了多少空间, 不用频繁获取而读磁盘, 节省资源. 每次用户如果上传的文件或者删除了文件, 那么又重新进行统计. 当然, 也可以把统计结果保存到数据库里.
复制代码 代码如下:

function countDirSize($dir)
{
$handle = opendir($dir);
while (false!==($FolderOrFile = readdir($handle)))
{
if($FolderOrFile != "." && $FolderOrFile != "..")
{
if(is_dir("$dir/$FolderOrFile")) {
$sizeResult += getDirSize("$dir/$FolderOrFile");
} else {
$sizeResult += filesize("$dir/$FolderOrFile");
}
}
}
closedir($handle);
return $sizeResult;
}

把字节转换为正常的K啊M啊之类的函数:
复制代码 代码如下:

function get_real_size($size) {

$kb = 1024; // Kilobyte
$mb = 1024 * $kb; // Megabyte
$gb = 1024 * $mb; // Gigabyte
$tb = 1024 * $gb; // Terabyte

if($size < $kb) {
return $size." B";
}else if($size < $mb) {
return round($size/$kb,2)." KB";
}else if($size < $gb) {
return round($size/$mb,2)." MB";
}else if($size < $tb) {
return round($size/$gb,2)." GB";
}else {
return round($size/$tb,2)." TB";
}
}

用法很简单:
复制代码 代码如下:

$size_zip=countDirSize("../zip/");
$size_zip=get_real_size($size_zip);

就这么简单了,呵呵。

复制代码 代码如下:

<?
/**
* File: fetch user directory use size
* Author: heiyeluren <heiyeluren_AT_gmail_com>
* Create: 2005-9-19 16:20
* Modifed: 2005-9-19 16:41
*/

/*** 基本函数 ***/

//计算目录大小
function countDirSize(dir)
{
handle = opendir(dir);
while (false!==(FolderOrFile = readdir(handle)))
{
if(FolderOrFile != "." && FolderOrFile != "..")
{
if(is_dir("dir/FolderOrFile")) {
sizeResult += getDirSize("dir/FolderOrFile");
} else {
sizeResult += filesize("dir/FolderOrFile");
}
}
}
closedir(handle);
return sizeResult;
}

//保存用户文件大小
function saveDirSize(userDir)
{
userDirSize = countDirSize(userDir);
if (!fp = fopen(userDir."/dir_size.txt", "w+")) {
die("Open file failed");
} else {
fwrite(fp, dirSize);
}
}

//获取用户目录的大小
function getDirSize(userDir)
{
user = addslashes(userDir);
sizeFile = userDir."/dir_size.txt";
if (!fp = fopen(sizeFile, "r") {
return 0;
} else {
dirSize = fread(fp, filesize(sizeFile));
}
return dirSize;
}
/*** 调用实例 ***/
user = "heiyeluren";
userPath = "./user/".user;

//如果用户执行了删除或者上传文件的操作就重新获取目录大小
if (action == "upload" || action == "delete") {
saveDirSize(userPath);
}

userDirSize = getDirSize(userPath)/1024;
echo "用户: ".user;
echo "占用空间: ".userDirSize;
?>

相关文章

PHP缓存技术的使用说明

在大部份情况下我们的网站都会使用数据库作为站点数据存储的容器。当你执行一个SQL查询时,典型的处理过程是:连接数据库->准备 SQL查询->发送查询到数据库->取得数据...

PHP字符转义相关函数小结(php下的转义字符串)

文章中有不正确的或者说辞不清的地方,麻烦大家指出了~~~与PHP字符串转义相关的配置和函数如下: 1.magic_quotes_runtime 2.magic_quotes_gpc 3....

PHP 函数学习简单小结

file_exists() 检查文件或目录是否存在    说明    bool file_exists ( string filename )    如果由 filename 指定的文件...

php include的妙用,实现路径加密

1、中转程序include.inc 复制代码 代码如下: <? include_once 'include/Base.php'; $path = ''; $url = isBase...

php浏览历史记录的方法

本文实例讲述了php浏览历史记录的方法。分享给大家供大家参考。具体实现方法如下: /** * 商品历史浏览记录 * $data 商品记录信息 */ private functi...