Calculate the weight of a directory (folder) in php - php

I am wanting to calculate the weight of a directory in php, then display the data as per the example below.
Example:
Storage
50 GB (14.12%) of 353 GB used
I have the following function, with which I show in a list the folders that are inside the root.
<?php
$dir = ('D:\data');
echo "Size : " Fsize($dir);
function Fsize($dir)
{
if (is_dir($dir))
{
if ($gd = opendir($dir))
{
$cont = 0;
while (($file = readdir($gd)) !== false)
{
if ($file != "." && $file != ".." )
{
if (is_dir($file))
{
$cont += Fsize($dir."/".$file);
}
else
{
$cont += filesize($dir."/".$file);
echo "file : " . $dir."/".$file . " " . filesize($dir."/".$file)."<br />";
}
}
}
closedir($gd);
}
}
return $cont;
}
?>
The size it shows me of the folder is 3891923, but it is not the real size, when validating the directory the real size is 191791104 bytes
Can you help me, please?

Your test for directory is incorrect here:
if (is_dir($file)) // This test is missing the directory component
{
$cont += Fsize($dir."/".$file);
}
else
Try:
if (is_dir("$dir/$file")) // This test adds the directory path
{
$cont += Fsize($dir."/".$file);
}
else
PHP offers a number of iterators that can simplify operations like this:
$path = "path/to/folder";
$Directory = new RecursiveDirectoryIterator($path);
$Iterator = new RecursiveIteratorIterator($Directory);
$Iterator->setFlags(FilesystemIterator::SKIP_DOTS);
$totalFilesize = 0;
foreach($Iterator as $file){
if ($file->isFile()) {
$totalFilesize += $file->getSize();
}
}
echo "Total: $totalFilesize";

Related

How to count number of files in folder in php?

I want to enable users to upload some files (pictures) in their own folders. But that should be possible only if that folders contain less than five pictures. If there are 5 pictures already, script has to let know user that his/her folder is full.
So, I wonder if there is function in php that count number of files in folder. Or any other way in php to do that? Thanks in advance.
Use the FilesystemIterator as shown:
$dir = "/path/to/folder";
$fi = new FilesystemIterator($dir, FilesystemIterator::SKIP_DOTS);
$fileCount = iterator_count($fi);
Nothing easier: use opendir() and readdir() just like follow:
<?php
$images_extension_array = array("jpg","jpeg","gif","png");
$dir = "/path/to/user/folder";
$dir_resource = opendir($dir);
$file_count = 0;
while (($file = readdir($dir_resource)) !== false) { // scan directory
$extension_from = strrpos($file,"."); // isolate extension index/offset
if ($extension_from && in_array(substr($file,$extension_from+1), $images_extension_array))
$file_count ++; //if has extension and that extension is "associated" with an image, count
}
if ($number_of_files == %) {
//do stuff
}
Obviously this doesn't take into account file extensions...
You can also use:
scandir() ---> read here
FilesystemIterator class (as dops's answer correctly suggest) ---> read here
You could just let PHP find the files for you...then count them.
$count = count(glob("$path_to_user_dir/*"));
I really like dops answer, but it will return the count of files, directories, and symlinks, which may not be the goal. If you just want a count of the local files in a directory, you can use:
$path = "/path/to/folder";
$fs = new FilesystemIterator($path);
foreach($fs as $file) {
$file->isFile() ? ++$filecount : $filecount;
}
This little function here is a modification to some code I found a little while ago that will also count all of the sub Folders and everything in those folders as well:
<?PHP
$folderCount = $fileCount = 0;
countStuff('.', $fileCount, $folderCount);
function countStuff($handle, &$fileCount, &$folderCount)
{
if ($handle = opendir($handle)) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
if (is_dir($entry)) {
echo "Folder => " . $entry . "<br>";
countStuff($entry, $fileCount, $folderCount);
$folderCount++;
} else {
echo "File => " . $entry . "<br>";
$fileCount++;
}
}
}
closedir($handle);
}
}
echo "<br>==============<br>";
echo "Total Folder Count : " . $folderCount . "<br>";
echo "Total File Count : " . $fileCount;
?>
NOTE: I will also post the original code that will just count the files and folders of the parent directory and not the sub-folders children below:
if ($handle = opendir('.')) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
if (is_dir($entry)) {
echo "Folder => " . $entry . "<br>";
countStuff($entry, $fileCount, $folderCount);
$folderCount++;
} else {
echo "File => " . $entry . "<br>";
$fileCount++;
}
}
}
echo "<br>==============<br>";
echo "Total Folder Count : " . $folderCount . "<br>";
echo "Total File Count : " . $fileCount;
closedir($handle);
}
You can use
$nbFiles=count(scandir('myDirectory'))-2;
(-2 is for removing "." and "..")

PHP – get the size of a directory

What is the best way to get the size of a directory in PHP? I'm looking for a lightweight way to do this since the directories I'll use this for are pretty huge.
There already was a question about this on SO, but it's three years old and the solutions are outdated.(Nowadays fopen is disabled for security reasons.)
Is the RecursiveDirectoryIterator available to you?
$bytes = 0;
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir));
foreach ($iterator as $i)
{
$bytes += $i->getSize();
}
You could try the execution operator with the unix command du:
$output = du -s $folder;
FROM: http://www.darian-brown.com/get-php-directory-size/
Or write a custom function to total the filesize of all the files in the directory:
function getDirectorySize($path)
{
$totalsize = 0;
$totalcount = 0;
$dircount = 0;
if($handle = opendir($path))
{
while (false !== ($file = readdir($handle)))
{
$nextpath = $path . '/' . $file;
if($file != '.' && $file != '..' && !is_link ($nextpath))
{
if(is_dir($nextpath))
{
$dircount++;
$result = getDirectorySize($nextpath);
$totalsize += $result['size'];
$totalcount += $result['count'];
$dircount += $result['dircount'];
}
else if(is_file ($nextpath))
{
$totalsize += filesize ($nextpath);
$totalcount++;
}
}
}
}
closedir($handle);
$total['size'] = $totalsize;
$total['count'] = $totalcount;
$total['dircount'] = $dircount;
return $total;
}

Load Random Images from Directory

I'd like to randomly load images from a directory and have a button somewhere that refreshes the entire page. Here's the current code I have now:
<?php
$a = array();
$dir = '../public/wp-content/uploads/2012/01';
if ($handle = opendir($dir)) {
while (false !== ($file = readdir($handle))) {
if (preg_match("/\.png$/", $file)) $a[] = $file;
elseif (preg_match("/\.jpg$/", $file)) $a[] = $file;
elseif (preg_match("/\.jpeg$/", $file)) $a[] = $file;
}
closedir($handle);
}
foreach ($a as $i) {
echo "<img src='" . $dir . '/' . $i . "' />";
}
?>
The problem is it loads all 400,000 images at once. I only want 30 to load. 30 random images from the directory. I tried looking up some code such as modifying the above to this:
<?php
$a = array();
$dir = '../public/wp-content/uploads/2012/01';
if ($handle = opendir($dir)) {
while (false !== ($file = readdir($handle))) {
if (preg_match("/\.png$/", $file)) $a[] = $file;
elseif (preg_match("/\.jpg$/", $file)) $a[] = $file;
elseif (preg_match("/\.jpeg$/", $file)) $a[] = $file;
}
closedir($handle);
}
foreach ($a as $i) {
echo "<img src='" . $dir . '/' . $i . "' />";
if (++$i == 2) break;
}
?>
But it seems to do absolutely nothing.. So if someone can help me get 30 random photos from that directory to load and have some type of reload button, that would be of great help.
Thank you in advance
Here is my solution with a cache:
<?php
define('CACHE_FILE', 'mycache.tmp');
define('CACHE_TIME', 20); // 20 seconds (for testing!)
define('IMG_COUNT', 30);
define('IMG_DIR', '../public/wp-content/uploads/2012/01');
/**
* Loads the list (an array) from the cache
* Returns FALSE if the file couldn't be opened or the cache was expired, otherwise the list (as an array) will be returned.
*/
function LoadListFromCache($cacheFile, $cacheTime)
{
if ( file_exists($cacheFile) )
{
$fileHandle = fopen($cacheFile, 'r');
if ( !$fileHandle )
return false;
// Read timestamp (separated by "\n" from the content)
$timestamp = intval( fgets($fileHandle) );
fclose($fileHandle);
// Expired?
if ( $timestamp+$cacheTime > time() )
return false;
else
{
// Unserialize the content!
$content = file_get_contents($cacheFile);
$content = substr( $content, strpos($content, "\n") );
$list = unserialize($content);
return $list;
}
}
return false;
}
/**
* Caches the passed array
* Returns FALSE if the file couldn't be opened, otherwise TRUE.
*/
function SaveListToCache($cacheFile, $list)
{
$fileHandle = fopen($cacheFile, 'w');
if ( $fileHandle === FALSE ) return false;
fwrite($fileHandle, time());
fwrite($fileHandle, "\n");
fwrite($fileHandle, serialize($list));
fclose($fileHandle);
return true;
}
/**
* Generates the list of all image files (png, jpg, jpeg) and caches it.
* Returns the list as an array.
*/
function GenerateList()
{
$a = array();
$dir = IMG_DIR;
if ($handle = opendir($dir))
{
while (false !== ($file = readdir($handle)))
{
if (preg_match("/\.png$/", $file)) $a[] = $file;
elseif (preg_match("/\.jpg$/", $file)) $a[] = $file;
elseif (preg_match("/\.jpeg$/", $file)) $a[] = $file;
}
closedir($handle);
}
SaveListToCache(CACHE_FILE, $a);
return $a;
}
function GetRandomImages($list, $count)
{
$listCount = count($list);
$randomEntries = array();
for ($i=0; $i<$count; $i++)
{
$randomEntries[] = $list[ rand(0, $listCount) ];
}
return $randomEntries;
}
// This code will execute the other functions!
$list = LoadListFromCache(CACHE_FILE, CACHE_TIME);
if ( $list === FALSE )
{
$list = GenerateList();
}
$images = GetRandomImages($list, IMG_COUNT);
foreach ($images as $image)
{
echo '<img src="', IMG_DIR.DIRECTORY_SEPARATOR.$image, '" />';
}
If you have 400,000 images then I think reading the entire directory everytime is going to be an expensive means of showing random images. I would use a database instead and store the file paths in it.
If you want to use your existing code then think of it this way. You have an array of length n containing image names. You want to generate thirty random numbers between 0 and n-1. Then display the image associated with that position in the array. I'm not a php expert, but here is some pseudocode:
$a = array();
$dir = '../public/wp-content/uploads/2012/01';
if (preg_match("/\.png$/", $file)) $a[] = $file;
elseif (preg_match("/\.jpg$/", $file)) $a[] = $file;
elseif (preg_match("/\.jpeg$/", $file)) $a[] = $file;
for ( i=0; i < 30; i++) {
//generate a random number between 0 and N-1
random = rand(0, $a.length - 1);
//display that image in the array
echo "<img src='" . $dir . '/' . $a[random] . "' />";
}
You need to create a new variable for the counter instead of using $i
For example, you can do this instead
$j = 0;
foreach ($a as $i) {
echo "<img src='" . $dir . '/' . $i . "' />";
$j++;
if ($j >= 30)
{
break;
}
}
EDIT: Perhaps for the random part you can first generate a random number between 0 and n-1 where n is the total number of the images and then just echo out the image from the array with the index number.
Instead of using foreach, I think you'll need a for loop instead.
$totalImgs = count($a);
$imgUsed = array();
for ($j = 0; $j < 30; $j++)
{
do
{
$randIndex = mt_rand(0, $totalImgs);
}
while ($imgUsed[$randIndex] === TRUE);
$imgUsed[$randIndex] = TRUE;
echo "<img src='" . $dir . '/' . $a[$randIndex] . "' />";
}
You should maybe only read 30 file from your directory. Stop looking in the directory when readdir return false or your array's length is 30.
This should work
$a = array();
$dir = '../public/wp-content/uploads/2012/01';
if ($handle = opendir($dir)) {
while (false !== ($file = readdir($handle)) && (count($a) <= 30) {
if (preg_match("/\.png$/", $file)) $a[] = $file;
elseif (preg_match("/\.jpg$/", $file)) $a[] = $file;
elseif (preg_match("/\.jpeg$/", $file)) $a[] = $file;
}
closedir($handle);
}
It may not execute (I didn't try). But the idea is here
For randomize the image: shuffle($a) should do the trick
in simplest way ,
you can use
find , sort , head
commands in linux,in conjuction with PHP's built in
exec()
function to get 30 random image links easily , the folowing snippet lists how to do it
(How to get random 30 image links in an array.)
<?php
$picdir = "directory/containing/pictures"; // directory containing only pictures
exec("find " . $picdir . " | sort -R | head -30 ",$links);
while(list($index,$val) = each($links) ) {
echo "<img src =" .$val . "> <br/>"; // shows image
}
?>
Here $links array contain random 30 image names(from folder) with complete path . This is used with img tag in echo to generate images
Here $picdir has the path of the directory having images and it is assumed that dirrectory is having only image files . in other case its only matter of modifying find command to exclude non image files(such as using grep command to exclude )

A minor issue while iteration of array in php.Guidance please

I have several files in a directory.I want to display all those filenames with the extension .txt and .jpeg
<?php
if ($handle = opendir("/home/work/collections/utils/")) {
while (false !== ($file = readdir($handle))) {
if ($file == '.' || $file == '..') {
continue;
}
$actual_file=pathinfo("/etrade/home/collections/utils");
if (($actual_file["extension"]== "txt") ||
($actual_file["extension"]== "jpg") ||
($actual_file["extension"]== "pdf")) {
//Require changes here.Dont know how to iterate and get the list of files
echo "<td>"."\n"." $actual_file['basename']."</a></td>";
}
}
closedir($handle);
}
Please help me on how to iterate and get the list of files .For instance I want all files with jpg extension in a seperate column and pdf files in a seperate column(since I am going to display in a table)
See if this does what you want (EDITED):
<?php
$ignoreFiles = array('.','..'); // Items to ignore in the directory
$allowedExtensions = array('txt','jpg','pdf'); // File extensions to display
$files = array();
$max = 0;
if ($handle = opendir("/home/work/collections/utils/")) {
while (false !== ($file = readdir($handle))) {
if (in_array($file, $ignoreFiles)) {
continue; // Skip items to ignore
}
// A simple(ish) way of getting a files extension
$extension = strtolower(array_pop($exploded = explode('.',$file)));
if (in_array($extension, $allowedExtensions)) { // Check if file extension is in allow list
$files[$extension][] = $file; // Create an array of each file type
if (count($files[$extension]) > $max) $max = count($files[$extension]); // Store the maximum column length
}
}
closedir($handle);
}
// Start the table
echo "<table>\n";
// Column headers
echo " <tr>\n";
foreach ($files as $extension => $data) {
echo " <th>$extension</th>\n";
}
echo " </tr>\n";
// Table data
for ($i = 0; $i < $max; $i++) {
echo " <tr>\n";
foreach ($files as $data) {
if (isset($data[$i])) {
echo " <td>$data[$i]</td>\n";
} else {
echo " <td />\n";
}
}
echo " </tr>\n";
}
// End the table
echo "</table>";
If you just want to display two lists of files (it's not clear what part you're having trouble with from your question) can't you just store the filenames in an array?
You don't seem to be getting the file details - you're getting the pathinfo for /etrade/home/collections/utils, but you never add the file name to it.
<?php
if ($handle = opendir("/home/work/collections/utils/")) {
while (false !== ($file = readdir($handle))) {
if ($file == '.' || $file == '..') {
continue;
}
$actual_file=pathinfo($file);
switch ($actual_file['extension'])
{
case ('jpg'):
$jpegfiles[] = $actual_file;
break;
case ('pdf'):
$pdffiles[] = $actual_file;
break;
}
}
closedir($handle);
}
echo "JPG files:"
foreach($jpegfiles as $file)
{
echo $file['basename'];
}
echo "PDF Files:"
foreach($pdffiles as $file)
{
echo $file['basename'];
}
?>
Obviously you can be cleverer with the arrays, and have use multi-dimensional arrays and do away with the switch if you want.

i want get the sum of files size in folder by php

I have a folder named files, how do I determine the sum of size of it's files?
With DirectoryIterator and SplFileInfo
$totalSize = 0;
foreach (new DirectoryIterator('/path/to/dir') as $file) {
if ($file->isFile()) {
$totalSize += $file->getSize();
}
}
echo $totalSize;
and in case you need that including subfolders:
$iterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator('/path/to/dir')
);
$totalSize = 0;
foreach ($iterator as $file) {
$totalSize += $file->getSize();
}
echo $totalSize;
And you can run $totalSize through the code we gave you to format 6000 to 6k for a more human readable output. You'd have to change all 1000s to 1024 though.
echo array_sum(array_map('filesize', glob('*')));
Well try this using filesize() to calculate file size while iterating through all the files and sub-directory files.
<?php
function get_dir_size($dir_name){
$dir_size =0;
if (is_dir($dir_name)) {
if ($dh = opendir($dir_name)) {
while (($file = readdir($dh)) !== false) {
if($file !=”.” && $file != “..”){
if(is_file($dir_name.”/”.$file)){
$dir_size += filesize($dir_name.”/”.$file);
}
/* check for any new directory inside this directory */
if(is_dir($dir_name.”/”.$file)){
$dir_size += get_dir_size($dir_name.”/”.$file);
}
}
}
}
}
closedir($dh);
return $dir_size;
}
$dir_name = “directory name here”;
/* 1048576 bytes == 1MB */
$total_size= round((get_dir_size($dir_name) / 1048576),2) ;
print “Directory $dir_name size : $total_size MB”;
?>
if you have access to exec function you can use this code:
exec("du {directory_path_you_want_see_size} -s 2>&1",$output);
echo intval($output[0]) ;
example:
exec("du /home/ -s 2>&1",$output);
echo intval($output[0]) ;

Categories