4
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【PHP】ディレクトリの容量を確認する方法

Last updated at Posted at 2019-03-23

disk_total_spacedisk_free_space関数が使える場合は簡単に計算できます。

bytes_check.php
<?php
$si_prefix = array('B', 'KB', 'MB', 'GB', 'TB', 'EB', 'ZB', 'YB');
$base = 1024;
$path = '/';

$total_bytes = disk_total_space($path);//全体サイズ
$free_bytes = disk_free_space($path);//空き容量

$used_bytes = $total_bytes - $free_bytes;
$class = min((int)log($used_bytes, $base), count($si_prefix) - 1);
echo '使用容量:'.sprintf('%1.2f', $used_bytes / pow($base,$class)).$si_prefix[$class];

##レンタルサーバーの場合
サーバーがレンタルサーバーなどの場合はdisk_total_spaceで正しい数値がでないため
下記のように直接ファイルサイズを足していきます。

bytes_check.php
<?php
//使用容量の数値(バイト)
function dir_size($dir) {
  $handle = opendir($dir);
  while ($file = readdir($handle)) {
    if ($file != '..' && $file != '.' && !is_dir($dir.'/'.$file)) {
      $mas += filesize($dir.'/'.$file);
    } else if (is_dir($dir.'/'.$file) && $file != '..' && $file != '.') {
      $mas += dir_size($dir.'/'.$file);
    }
  }
  return $mas;
}

//数値の単位を変更
function used_bytes($dir){
  $si_prefix = array('B', 'KB', 'MB', 'GB', 'TB', 'EB', 'ZB', 'YB');
  $base = 1024;
  $dir_size = dir_size($dir);
  $class = min((int)log($dir_size, $base), count($si_prefix) - 1);
  $used_bytes = sprintf('%1.2f', $dir_size / pow($base,$class)).$si_prefix[$class];
  return $used_bytes;
}
echo "使用容量:".used_bytes(dirname(__FILE__));

used_bytes($dir)で出力します。
$dirには絶対パスを指定してください。

4
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?