Last Updated: October 02, 2016
·
293
· wapmorgan

FilesystemOperations in PHP

<?php
namespace wapmorgan\FilesystemOperations;
class Filesystem {
/**
* Recursively removes all files from folder and root folder.
/
static public function removeDir($dir) {
$dp = opendir($dir);
while (($file = readdir($dp)) !== false) {
if ($file == '.' || $file == '..') continue;
if (is_dir($dir.'/'.$file))
self::removeDir($dir.'/'.$file);
else
unlink($dir.'/'.$file);
}
closedir($dp);
return rmdir($dir);
}
/
*
* Counts size of all included files in folder.
/
static public function countDirSize($dir) {
$size = 0;
$dp = opendir($dir);
while (($file = readdir($dp)) !== false) {
if ($file == '.' || $file == '..') continue;
if (is_dir($dir.'/'.$file))
$size += self::countDirSize($dir.'/'.$file);
else
$size += filesize($dir.'/'.$file);
}
closedir($dp);
return $size;
}
/
*
* This method is applicable, when source and target locations stays on different filesystems. To check it, call differentFilesystems firstly.
/
static public function emulateDirMove($source, $target) {
if (!isdir($target)) mkdir($target, 0755, true);
$dd = opendir($source);
while (($file = readdir($dd)) !== false) {
if ($file == '.' || $file == '..') continue;
if (is
dir($source.'/'.$file))
if (!self::emulateDirMove($source.'/'.$file, $target.'/'.$file))
return false;
else if (is_link($source.'/'.$file)) {
$link = readlink($source.'/'.$file);
symlink($link, $target.'/'.$file);
if (!unlink($source.'/'.$file))
return false;
}
else
if (!rename($source.'/'.$file, $target.'/'.$file))
return false;
}
closedir($dd);
return rmdir($source);
}
/
*
* Checks that two files stays on different filesystems.
/
static public function differentFilesystems($path1, $path2) {
if (disktotalspace($path1) != disktotalspace($path2)
|| diskfreespace($path1) != diskfreespace($path2))
return true;
return false;
}
/
*
* Deletes files from folder until it has needed size.
/
static public function truncateDir($dir, $neededSize) {
$size = self::countDirSize($dir);
if ($size > $neededSize) {
$files = self::getFilesList($dir);
asort($files);
while ($size > $neededSize && !empty($files)) {
$file = key($files);
$size -= filesize($dir.'/'.$file);
unlink($dir.'/'.$file);
}
}
}
/
*
* Returns list of files in folder with their size or time.
*/
static public function getFilesList($dir, $attrib = 'size') {
$files = array();
$dd = opendir($dir);
while (($file = readdir($dir)) !== false) {
if (inarray($file, array('.', '..'))) continue;
if (is
file($dir.'/'.$file)) {
switch ($attrib) {
case 'size':
$files[$file] = filesize($dir.'/'.$file);
break;
case 'time':
$files[$file] = filemtime($dir.'/'.$file);
break;
}
}
}
closedir($dd);
return $files;
}
}