The general program idea is to use the recursion to calculate how much space the directory occupies, and then the space to occupy the value of the text file, so long as the access to this TXT file to know how much space occupied, do not have frequent access to read disk, save resources. Each time a user uploads a file or deletes a file, it is then counted again. Of course, you can also save the results to the database.
Copy Code code as follows:
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;
}
Convert bytes to normal K-M-ah functions:
Copy Code code as follows:
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 ";
}
}
The usage is simple:
Copy Code code as follows:
$size _zip=countdirsize (".. /zip/");
$size _zip=get_real_size ($size _zip);
It's so simple, hehe.
Copy Code code as follows:
?
/**
* File:fetch User Directory use size
* Author:heiyeluren * Create:2005-9-19 16:20
* Modifed:2005-9-19 16:41
*/
/*** Basic Function ***/
Calculate Directory Size
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;
}
Save user File Size
function Savedirsize (userdir)
{
Userdirsize = Countdirsize (Userdir);
if (!FP = fopen (userdir.) /dir_size.txt "," w+ ")") {
Die ("Open file failed");
} else {
Fwrite (FP, dirsize);
}
}
Get the size of the user directory
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;
}
/*** Invocation Instance ***/
user = "Heiyeluren";
UserPath = "./user/". User;
Retrieve the directory size if the user performs a delete or upload file
if (action = = "Upload" | | = action = "Delete") {
Savedirsize (UserPath);
}
Userdirsize = Getdirsize (userpath)/1024;
echo "User:". User;
echo "Occupy space:". userdirsize;
?>