PHP:获取文件夹用户空间并返回与总用户空间相关的百分比


PHP: get folder user space and return as percentage related to total user space

我正在做一个函数来计算当前使用的空间(计算目录大小)并与可用的用户空间(例如10MB)进行比较,然后它将返回一个百分比数字来填充进度条。

function getDirSpaceLeft($totalSpace) {
   $f = 'data/';
   $io = popen ( '/usr/bin/du -sk ' . $f, 'r' );
   $size = fgets ( $io, 4096);
   $size = substr ( $size, 0, strpos ( $size, "'t" ) );
   pclose ( $io );
   $current = $totalSpace - $size;
   $precent = $current * 100 / 2;
   return $precent;
}

但是使用这个代码,如果我传递10Mb(10485760)的值给函数,它将返回一个奇怪的数字,如523557400。

我想我做错了什么,谢谢。

这是我发现的一个函数(不是我的),它以字节为单位返回文件夹(包括子文件夹)中文件使用的大小:

/*  Get size of files in folder including subfolders, in bytes.
    From: https://gist.github.com/eusonlito/5099936
*/
function getSizeUsed($dir) {
    $size = 0;
    foreach (glob(rtrim($dir, '/').'/*', GLOB_NOSORT) as $each)
        $size += is_file($each) ? filesize($each) : getSizeUsed($each);
    return $size;
}

然后可以计算总使用量的百分比,如下所示:

$total = 10000000;
$dir = "data/";
echo (getSizeUsed($dir)/$total)*100;

虽然这不是一个修复您的代码,这是我做我的…

<?php
// folder to check
$dir = '/';
// get disk space free (in bytes)
$disk_free = disk_free_space($dir);
// get disk space total (in bytes)
$disk_total = disk_total_space($dir);
// calculate the disk space used (in bytes)
$disk_used = $disk_total - $disk_free;
// percentage of disk used
$disk_used_p = sprintf('%.2f',($disk_used / $disk_total) * 100);
// this function will convert bytes value to KB, MB, GB and TB
function convertSize( $bytes )
{
        $sizes = array( 'B', 'KB', 'MB', 'GB', 'TB' );
        for( $i = 0; $bytes >= 1024 && $i < ( count( $sizes ) -1 ); $bytes /= 1024, $i++ );
                return( round( $bytes, 2 ) . " " . $sizes[$i] );
}
// format the disk sizes using the function (B, KB, MB, GB and TB)
$disk_free = convertSize($disk_free);
$disk_used = convertSize($disk_used);
$disk_total = convertSize($disk_total);
echo '<ul>';
echo '<li>Total: '.$disk_total.'</li>';
echo '<li>Used: '.$disk_used.' ('.$disk_used_p.'%)</li>';
echo '<li>Free: '.$disk_free.'</li>';
echo '</ul>';
?>

PHP手册:

  1. disk_free_space ()