Function php with loop - php

In index.php I have arrays listing folders. Function.php has code that counts the size of the folder. The code works when I type the folder name manually. I don't know how to make the code in function.php count for all folders in index.php. In index.php I made a loop foreach ($nameFolders as $index => $value) {echo $nameFolders[$index];} but it does not work in function.php $disk_used = foldersize ($nameFolders[$index]);
index.php
$nameFolders = array("nameFolder1", "nameFolder2", "nameFolder3");
foreach ($nameFolders as $index => $value) {
echo $nameFolders[$index];
}
include 'function.php';
function.php
$units = explode(' ', 'B KB MB GB');
$disk_used = foldersize($nameFolders[$index]);
$totalSize = format_size($disk_used);
function foldersize($path)
{
$total_size = 0;
$files = scandir($path);
$cleanPath = rtrim($path, '/').'/';
foreach ($files as $t) {
if ($t <> "." && $t <> "..") {
$currentFile = $cleanPath.$t;
if (is_dir($currentFile)) {
$size = foldersize($currentFile);
$total_size += $size;
} else {
$size = filesize($currentFile);
$total_size += $size;
}
}
}
return $total_size;
}
function format_size($size)
{
global $units;
$mod = 1024;
for ($i = 0; $size > $mod; $i++) {
$size /= $mod;
}
$endIndex = strpos($size, ".") + 3;
return substr($size, 0, $endIndex).' '.$units[$i];
}

There are several things wrong with your code, starting with the include order. If you include (and thus declare) the functions AFTER your loop, you cannot use them inside the loop; I understand that you are trying to print all the folders with their sizes.
index.php
<?php
include_once('function.php'); // this needs to happen before.
$name_folders = array('nameFolder1', 'nameFolder2', 'nameFolder3');
// no need for key => value here if you don't use that
foreach ($name_folders as $folder) {
$disk_used = folder_size($folder);
$totalSize = format_size($disk_used);
echo "$folder: $totalSize\n";
}
function.php
<?php
$units = explode(' ', 'B KB MB GB');
function folder_size($path)
{
$total_size = 0;
$files = scandir($path);
$cleanPath = rtrim($path, '/').'/';
foreach ($files as $t) {
if ($t <> "." && $t <> "..") {
$currentFile = $cleanPath.$t;
if (is_dir($currentFile)) {
$size = folder_size($currentFile);
$total_size += $size;
} else {
$size = filesize($currentFile);
$total_size += $size;
}
}
}
return $total_size;
}
function format_size($size)
{
global $units;
$mod = 1024;
for ($i = 0; $size > $mod; $i++) {
$size /= $mod;
}
$endIndex = strpos($size, ".") + 3;
return substr($size, 0, $endIndex).' '.$units[$i];
}
Please note that this "include function.php" style of PHP is how we did it in 1999, and it's not really a modern practice. Same goes for the use of global there. Try sticking to ONE naming convention: you mix camelCase with snake_case.

Related

Recursive function to get filesize in PHP

I am working on a PHP function that will scan a given folder and return the total size of all the files in the folder. My issue is that, even though it works for files stored in the root of that folder, it doesn't work for files in any subfolder. My code is:
function get_total_size($system)
{
$size = 0;
$path = scandir($system);
unset($path[0], $path[1]);
foreach($path as $file)
{
if(is_dir($file))
{
get_total_size("{$system}/{$file}");
}
else
{
$size = $size + filesize("{$system}/{$file}");
}
}
$size = $size / 1024;
return number_format($size, 2, ".", ",");
}
I'm unsetting the 0th and 1st elements of the array since these are the dot and the double dot to go up a directory. Any help would be greatly appreciated
You may try this procedure. When you check this file is_dir then you have to count the file size also. And when you check is_dir you have to concat it with root directory otherwise it show an error.
function get_total_size($system)
{
$size = 0;
$path = scandir($system);
unset($path[0], $path[1]);
foreach($path as $file)
{
if(is_dir($system.'/'.$file))
{
$size+=get_total_size("{$system}/{$file}");
}
else
{
$size = $size + filesize("{$system}/{$file}");
}
}
$size = $size / 1024;
return number_format($size, 2, ".", ",");
}
I think it will work fine
Happy coding :)
You forgot to count the size of the subfolders. you have to add it to the $size variable.
function get_total_size($system)
{
$size = 0;
$path = scandir($system);
unset($path[0], $path[1]);
foreach($path as $file)
{
if(is_dir($file))
{
$size += get_total_size("{$system}/{$file}"); // <--- HERE
}
else
{
$size = $size + filesize("{$system}/{$file}");
}
}
return $size;
}
This might however give a problem because you are using the number_format function. I would not do this and add the formatting after receiving the result of the get_total_size function.
you can use recursive directory iterator for the same. Have a look on below solution:
<?php
$total_size = 0;
$di = new RecursiveDirectoryIterator('/directory/path');
foreach (new RecursiveIteratorIterator($di) as $filename => $file) {
if($file->isFile()) {
echo $filename . ' - ' . $file->getSize() . ' bytes <br/>';
$total_size += $file->getSize();
}
}
echo $total_size; //in bytes
?>
The recursiveIterator family of classes could be of use to you.
function filesize_callback( $obj, &$total ){
foreach( $obj as $file => $info ){
if( $obj->isFile() ) {
echo 'path: '.$obj->getPath().' filename: '.$obj->getFilename().' filesize: '.filesize( $info->getPathName() ).BR;
$total+=filesize( $info->getPathName() );
} else filesize_callback( $info,&$total );
}
}
$total=0;
$folder='C:\temp';
$iterator=new RecursiveIteratorIterator( new RecursiveDirectoryIterator( $folder, RecursiveDirectoryIterator::KEY_AS_PATHNAME ), RecursiveIteratorIterator::CHILD_FIRST );
call_user_func( 'filesize_callback', $iterator, &$total );
echo BR.'Grand-Total: '.$total.BR;

How to get 15 random images from a folder in Wordpress?

I need to get 15 random images from a folder and show them on a page:
I tried the following code, however it did not do what I wanted:
$string =array();
$filePath='wp-content/themes/tema/img-test/';
$dir = opendir($filePath);
while ($file = readdir($dir)) {
if (eregi("\.png",$file) || eregi("\.jpg",$file) || eregi("\.gif",$file) ) {
$string[] = $file;
}
}
while (sizeof($string) != 0){
$img = array_pop($string);
echo "<img src='$filePath$img' width='100px'/>";
}
So, you have all the files in $string array, that's good.
You can either use the rand() function to get some random integer in the arrays size:
$string = ['img1.jpg','img2.jpg','img3.jpg'];
$rand = rand(0,count($string)-1);
echo $string[$rand];
You would have to loop that.
Or, you could use array_rand() which will automate all that:
$string = ['img1.jpg','img2.jpg','img3.jpg'];
$amount = 3;
$rand_arr = array_rand($string, $amount);
for($i=0;$i<$amount;$i++) {
echo $string[$rand_arr[$i]] ."<br>";
}
You could do this using the glob() function native to PHP. It will get all files in a directory. Following that you can pick one file from the retrieved list.
$randomFiles = array();
$files = glob($dir . '/*.*');
$file = array_rand($files);
for ($i = 0; $i <= 15; $i++) {
$randomFiles[] = $files[$file];
}
Use this code. Your random image will be available in $arRandomFiles.
$filePath = 'wp-content/themes/tema/img-test/';
$files = glob($filePath. '*.{jpeg,gif,png}', GLOB_BRACE);
$arKeys = array_rand($files, 15);
$arRandomFiles = array();
foreach ($arKeys as $key) {
$arRandomFiles[] = $files[$key];
}
var_dump($arRandomFiles);
Simple function that handles that
<?php
function getImg( $path ) {
$filePath= $path . '*';
$imgs = glob( $filePath );
if( $imgs ) {
$i = 1;
foreach( $imgs as $img ) {
if( $i <= 15 ) {
$ext = pathinfo( $img, PATHINFO_EXTENSION );
if( in_array( $ext, array( 'jpg', 'jpeg', 'png', 'gif' ) ) )
$r[] = $img;
}
else
break;
$i++;
}
shuffle( $r );
return $r;
}
else
return array();
}
print_r( getImg( 'wp-content/themes/tema/img-test/' ) );
You can try function like:
function getRandomFile($directory)
{
$directoryIterator = new DirectoryIterator($directory);
$count = iterator_count($directoryIterator) - 2;
foreach ($directoryIterator as $fileInfo) {
$last = $fileInfo->getRealPath();
if ($fileInfo->isFile() && (rand() % $count == 0)) {
break;
}
}
return $last;
}

Getting RecursiveIteratorIterator to skip a specified directory

I'm using this function to get the file size & file count from a given directory:
function getDirSize($path) {
$total_size = 0;
$total_files = 0;
$path = realpath($path);
if($path !== false){
foreach(new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS)) as $object) {
$total_size += $object->getSize();
$total_files++;
}
}
$t['size'] = $total_size;
$t['count'] = $total_files;
return $t;
}
I need to skip a single directory (in the root of $path). Is there a simple way to do this? I looked at other answers referring to FilterIterator, but I'm not very familiar with it.
If you don't want to involve a FilterIterator you can add a simple path match:
function getDirSize($path, $ignorePath) {
$total_size = 0;
$total_files = 0;
$path = realpath($path);
$ignorePath = realpath($path . DIRECTORY_SEPARATOR . $ignorePath);
if($path !== false){
foreach(new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS)) as $object) {
if (strpos($object->getPath(), $ignorePath) !== 0) {
$total_size += $object->getSize();
$total_files++;
}
}
}
$t['size'] = $total_size;
$t['count'] = $total_files;
return $t;
}
// Get total file size and count of current directory,
// excluding the 'ignoreme' subdir
print_r(getDirSize(__DIR__ , 'ignoreme'));

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;
}

How to breakdown folder path in php

I am trying to break down a folder path
eg: home/player/jay/profile/pictures:
home
home/players
home/players/jay
home/players/jay/profile
home/players/jay/profile/pictures
i tryed using this but i cant get it to displaying right
$new_folders = explode("/","home/player/jay/profile/pictures");
for ($i = 0; $i < sizeof($new_folders); $i++) {
for ($r = 0; $r < $i + 1; $r++) {
$create_new_path .= $new_folders[$r];
if ($r != $i) {
$create_new_path .= "/";
}
}
//ftp_mkdir($conn_id, "httpdocs/user_images/".$create_new_path);
//ftp_chmod($conn_id, 0777, "httpdocs/user_images/".$create_new_path);
}
$breakdown = array();
$dirs = explode('/', 'home/player/jay/profile/pictures');
$path = '';
foreach($dirs as $dir) {
$path .= ($path !== '' ? '/' : '') . $dir;
$breakdown[] = $path;
}
// result is in $breakdown

Categories