How to count number of files in folder in php? - 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 "..")

Related

Calculate the weight of a directory (folder) in 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";

how to check if folder contains only files with php

I want to check if a folder contains at least 1 real file. I tried this code:
$dir = "/dir/you/want/to/scan";
$handle = opendir($dir);
$folders = 0;
$files = 0;
while(false !== ($filename = readdir($handle))){
if(($filename != '.') && ($filename != '..')){
if(is_dir($filename)){
$folders++;
} else {
$files++;
}
}
}
echo 'Number of folders: '.$folders;
echo '<br />';
echo 'Number of files: '.$files;
when in folder scan are 1 subfolder and 2 real files; the code above gives me as output:
Number of folders: 0
Number of files: 3
So it seems that a subfolder is seen as a file. But i want only real files to be checked. How can i achieve that?
You can do this job easily using glob():
$dir = "/dir/you/want/to/scan";
$folders = glob($dir . '/*', GLOB_ONLYDIR);
$files = array_filter(glob($dir . '/*'), 'is_file');
echo 'Number of folders: ' . count($folders);
echo '<br />';
echo 'Number of files: ' . count($files);
based on your first line, where you specify a path, which is different to your scripts path, you should combine $dir and the $filename in the is_dir if-clause.
Why?
Because if your script is on:
/var/web/www/script.php
and you check the $dir:
/etc/httpd
which contains the subfolder "conf", your script will check for the subfolder /var/web/www/conf
You can use scandir
scandir — List files and directories inside the specified path
<?php
$dir = "../test";
$handle = scandir($dir);
$folders = 0;
$files = 0;
foreach($handle as $filename)
{
if(($filename != '.') && ($filename != '..'))
{
if(is_dir($filename))
{
$folders++;
}
else
{
$files++;
}
}
}
echo 'Number of folders: '.$folders;
echo '<br />';
echo 'Number of files: '.$files;
?>

Search for a folder and and get the content of the files inside

I'm trying to search for a folder and retrieve the files inside of the folder (get content) I'm able to search for the folder using the follow code but I can't pass from there I can't see the content an retrieve the files inside. The files inside will be txt files and I would like to be able to open and see then.
How can achieve what i want? Thank you.
<?php
$dirname = "C:\windows";//Directory to search in. *Must have a trailing slash*
$findme = $_POST["search"];
$dir = opendir($dirname);
while(false != ($file = readdir($dir))){//Loop for every item in the directory.
if(($file != ".") and ($file != "..") and ($file != ".DS_Store") and ($file !=
"search.php"))//Exclude these files from the search
{
$pos = stripos($file, $findme);
if ($pos !== false){
$thereisafile = true;//Tell the script something was found.
echo'' . $file . '<br>';
}else{
}
}
}
if (!isset($thereisafile)){
echo "Nothing was found.";//Tell the user nothing was found.
echo '<img src="yourimagehere.jpg"/>';//Display an image, when nothing was found.
}
?>
New code
<?php
$dirname = "C:\\Windows\\";//Directory to search in. *Must have a trailing slash*
$findme = 'maxlink'; //$_POST["search"];
$files = scandir($dirname);
foreach ($files AS $file)
{
if ($file == '.' or $file == '..' or $file == '.DS_Store' or $file == 'search.php') continue;
if (stripos($file, $findme) !== false)
{
$found = true;
echo 'FOUND FILE ' . $file . '<hr>';
echo 'OPENING IT:<br>';
echo file_get_contents($dirname . $file);
echo '<hr>';
}
else
{
echo 'not found: ' . $file . '<br>';
}
}
if (!isset($found))
{
echo "Nothing was found.";//Tell the user nothing was found.
echo '<img src="yourimagehere.jpg"/>';//Display an image, when nothing was found.
}
The following code uses a recursive function for searching the directory. I hope it’ll solve your problem.
function scandir_r($dir){
$files = array_diff(scandir($dir), array(".", ".."));
$arr = array();
foreach($files as $file){
$arr[] = $dir.DIRECTORY_SEPARATOR.$file;
if(is_dir($dir.DIRECTORY_SEPARATOR.$file)){
$arr = array_merge($arr, scandir_r($dir.DIRECTORY_SEPARATOR.$file));
}
}
return($arr);
}
$dirname = "C:\windows";
$findme = "/".preg_quote($_POST["search"], "/")."/";
$files = preg_grep($findme, scandir_r($dirname));
if(sizeof($files)){
foreach($files as $file){
$_file = $dirname.DIRECTORY_SEPARATOR.$file;
echo "$file<br/>";
}
}
else{
echo "Nothing was found.";
echo "<img src=\"yourimagehere.jpg\"/>";
}

Pull all images from multiple directories and display them with PHP

I have a folder on my server called 'images', and within that folder I could have a single folder to as many as 10 folders that contain images.
Instead of writing a tag for each image
<img src="images/people/001.jpg">
<img src="images/landscape/001.jpg">
etc etc
Can I use PHP to get all the images in all the folders in the main directory 'images'?
I have VERY little experience with PHP, so this is something I am struggling with.
I need php to return an array of '<div class="box"><img src="images/FOLDER/IMAGENAME.jpg"></div>'
Maybe someone can help.
function ListFiles($dir) {
if($dh = opendir($dir)) {
$files = Array();
$inner_files = Array();
while($file = readdir($dh)) {
if($file != "." && $file != ".." && $file[0] != '.') {
if(is_dir($dir . "/" . $file)) {
$inner_files = ListFiles($dir . "/" . $file);
if(is_array($inner_files)) $files = array_merge($files, $inner_files);
} else {
array_push($files, $dir . "/" . $file);
}
}
}
closedir($dh);
return $files;
}
}
foreach (ListFiles('/path/to/images') as $key=>$file){
echo "<div class=\"box\"><img src=\"$file\"/></div>";
}
Something like this?
A simpler soluton. You can use built-in glob function. Assuming that all of your images are .jpg:
$result = array();
$dir = 'images/';
foreach(glob($dir.'*.jpg') as $filename) {
$result[] = "<div class=\"box\"><img src=\"$filename\"></div>";
}
Then you can echo each element of $result or whatever you want.

PHP read sub-directories and loop through files how to?

I need to create a loop through all files in subdirectories. Can you please help me struct my code like this:
$main = "MainDirectory";
loop through sub-directories {
loop through filels in each sub-directory {
do something with each file
}
};
Use RecursiveDirectoryIterator in conjunction with RecursiveIteratorIterator.
$di = new RecursiveDirectoryIterator('path/to/directory');
foreach (new RecursiveIteratorIterator($di) as $filename => $file) {
echo $filename . ' - ' . $file->getSize() . ' bytes <br/>';
}
You need to add the path to your recursive call.
function readDirs($path){
$dirHandle = opendir($path);
while($item = readdir($dirHandle)) {
$newPath = $path."/".$item;
if(is_dir($newPath) && $item != '.' && $item != '..') {
echo "Found Folder $newPath<br>";
readDirs($newPath);
}
else{
echo ' Found File or .-dir '.$item.'<br>';
}
}
}
$path = "/";
echo "$path<br>";
readDirs($path);
You probably want to use a recursive function for this, in case your sub directories have sub-sub directories
$main = "MainDirectory";
function readDirs($main){
$dirHandle = opendir($main);
while($file = readdir($dirHandle)){
if(is_dir($main . $file) && $file != '.' && $file != '..'){
readDirs($file);
}
else{
//do stuff
}
}
}
didn't test the code, but this should be close to what you want.
I like glob with it's wildcards :
foreach (glob("*/*.txt") as $filename) {
echo "$filename\n";
}
Details and more complex scenarios.
But if You have a complex folders structure RecursiveDirectoryIterator is definitively the solution.
Come on, first try it yourself!
What you'll need:
scandir()
is_dir()
and of course foreach
http://php.net/manual/en/function.is-dir.php
http://php.net/manual/en/function.scandir.php
Another solution to read with sub-directories and sub-files (set correct foldername):
<?php
$path = realpath('samplefolder/yorfolder');
foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path)) as $filename)
{
echo "$filename <br/>";
}
?>
Minor modification on what John Marty posted, if we can safely eliminate any items that are named . or ..
function readDirs($path){
$dirHandle = opendir($path);
while($item = readdir($dirHandle)) {
$newPath = $path."/".$item;
if (($item == '.') || ($item == '..')) {
continue;
}
if (is_dir($newPath)) {
pretty_echo('Found Folder '.$newPath);
readDirs($newPath);
} else {
pretty_echo('Found File: '.$item);
}
}
}
function pretty_echo($text = '')
{
echo $text;
if (PHP_OS == 'Linux') {
echo "\r\n";
}
else {
echo "</br>";
}
}
<?php
ini_set('max_execution_time', 300); // increase the execution time of the file (in case the number of files or file size is more).
class renameNewFile {
static function copyToNewFolder() { // copies the file from one location to another.
$main = 'C:\xampp\htdocs\practice\demo'; // Source folder (inside this folder subfolders and inside each subfolder files are present.)
$main1 = 'C:\xampp\htdocs\practice\demomainfolder'; // Destination Folder
$dirHandle = opendir($main); // Open the source folder
while ($file = readdir($dirHandle)) { // Read what's there inside the source folder
if (basename($file) != '.' && basename($file) != '..') { // Ignore if the folder name is '.' or '..'
$folderhandle = opendir($main . '\\' . $file); // Open the Sub Folders inside the Main Folder
while ($text = readdir($folderhandle)) {
if (basename($text) != '.' && basename($text) != '..') { // Ignore if the folder name is '.' or '..'
$filepath = $main . '\\' . $file . '\\' . $text;
if (!copy($filepath, $main1 . '\\' . $text)) // Copy the files present inside the subfolders to destination folder
echo "Copy failed";
else {
$fh = fopen($main1 . '\\' . 'log.txt', 'a'); // Write a log file to show the details of files copied.
$text1 = str_replace(' ', '_', $text);
$data = $file . ',' . strtolower($text1) . "\r\n";
fwrite($fh, $data);
echo $text . " is copied <br>";
}
}
}
}
}
}
static function renameNewFileInFolder() { //Renames the files into desired name
$main1 = 'C:\xampp\htdocs\practice\demomainfolder';
$dirHandle = opendir($main1);
while ($file = readdir($dirHandle)) {
if (basename($file) != '.' && basename($file) != '..') {
$filepath = $main1 . '\\' . $file;
$text1 = strtolower($filepath);
rename($filepath, $text1);
$text2 = str_replace(' ', '_', $text1);
if (rename($filepath, $text2))
echo $filepath . " is renamed to " . $text2 . '<br/>';
}
}
}
}
renameNewFile::copyToNewFolder();
renameNewFile::renameNewFileInFolder();
?>
$allFiles = [];
public function dirIterator($dirName)
{
$whatsInsideDir = scandir($dirName);
foreach ($whatsInsideDir as $fileOrDir) {
if (is_dir($fileOrDir)) {
dirIterator($fileOrDir);
}
$allFiles.push($fileOrDir);
}
return $allFiles;
}

Categories