找回密码
 注册
搜索
热搜: 回贴
微赢网络技术论坛 门户 网络编程 PHP 查看内容

php获取某个目录大小

2009-12-21 17:49| 发布者: admin| 查看: 72| 评论: 0|原作者: 青鸾峰

  大致就是不知道目录下面又多少层目录, 也不知道又多少文件, 需要统计占用空间大小, 这个可以用在 相册/数据库占用/网络U盘 等程序中.
  大致程序思想就是使用递规来计算目录占用空间多少, 然后再把这个占用空间的值写进文本文件里, 那么只要访问这个txt文件就知道占用了多少空间, 不用频繁获取而读磁盘, 节省资源. 每次用户如果上传的文件或者删除了文件, 那么又重新进行统计. 当然, 也可以把统计结果保存到数据库里.
/**
* File: fetch user directory use size
* Author: heiyeluren
* 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;
?>

最新评论

QQ|小黑屋|最新主题|手机版|微赢网络技术论坛 ( 苏ICP备08020429号 )

GMT+8, 2024-9-30 01:36 , Processed in 0.162291 second(s), 12 queries , Gzip On, MemCache On.

Powered by Discuz! X3.5

© 2001-2023 Discuz! Team.

返回顶部