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;
?>
Related
Following folder structure:
/files/<user_id>/<filename>.txt
Examples:
`/files/15/file1.txt`
`/files/15/file2.txt`
`/files/21/file1.txt`
`/files/23/file1.txt`
I need to count the total number of files in each subfolder, but only on the subfolder level. Meaning, if there is another folder, like /files/23/dir/file1.txt, then this folder and its content should not be counted.
Output:
<folder_name>: <folder_count> files
Examples:
15: 23 files
21: 2 files
23: 5 files
How can one do a recursive count for subdirectories, but ignore directories in the subdirectory?
Thanks
Edit:
My code so far:
<?php
// integer starts at 0 before counting
$i = 0;
$path = '../../../../../../../home/bpn_sftp';
$dirs = glob($path . '/*' , GLOB_ONLYDIR);
foreach($dirs as $dir){
while (($file = readdir($dir)) !== false){
if (!in_array($file, array('.', '..')) && !is_dir($dir.$file))
{
$file_count = count( glob($dir.'*.txt') );
echo $dir." has ".$file_count." files<br>";
$i++;
}
}
}
echo "Total count: ".$i." files";
?>
Managed to make it work with a recursive folder scan, limiting the file count to the filetype I am looking for.
<?php
// integer starts at 0 before counting
$i = 0;
$path = './test';
$dirs = glob($path . '/*' , GLOB_ONLYDIR);
foreach($dirs as $dir){
$file_count = count( glob($dir.'/*.txt') );
echo $dir." has ".$file_count." files<br>";
$i++;
}
echo "Total count: ".$i." files";
?>
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\"/>";
}
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 "..")
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.
This question already has answers here:
Getting the names of all files in a directory with PHP
(15 answers)
Closed 6 months ago.
I have the code below that lists all the images in a folder, the problem is that it finds some files ( a . and a ..) that I am not sure what they are so I am not sure how to prevent them from showing up. I am on a windows XP machine, any help would be great, thanks.
Errors: Warning: rename(images/.,images/.) [function.rename]: No error
in C:\wamp\www\Testing\listPhotosA.php on line 14
Warning: rename(images/..,images/..) [function.rename]: No error in
C:\wamp\www\Testing\listPhotosA.php on line 14
Code:
<?php
define('IMAGEPATH', 'images/');
if (is_dir(IMAGEPATH)){
$handle = opendir(IMAGEPATH);
}
else{
echo 'No image directory';
}
$directoryfiles = array();
while (($file = readdir($handle)) !== false) {
$newfile = str_replace(' ', '_', $file);
rename(IMAGEPATH . $file, IMAGEPATH . $newfile);
$directoryfiles[] = $newfile;
}
foreach($directoryfiles as $directoryfile){
if(strlen($directoryfile) > 3){
echo '<img src="' . IMAGEPATH . $directoryfile . '" alt="' . $directoryfile . '" /> <br>';
}
}
closedir($handle); ?>
I like PHP's glob function.
foreach(glob(IMAGEPATH.'*') as $filename){
echo basename($filename) . "\n";
}
glob() is case sensitive and the wildcard * will return all files, so I specified the extension here so you don't have to do the filtering work
$d = 'path/to/images/';
foreach(glob($d.'*.{jpg,JPG,jpeg,JPEG,png,PNG}',GLOB_BRACE) as $file){
$imag[] = basename($file);
}
Use glob function.
<?php
define('IMAGEPATH', 'images/');
foreach(glob(IMAGEPATH.'*') as $filename){
$imag[] = basename($filename);
}
print_r($imag);
?>
You got all images in array format
To get all jpg images in all dirs and subdirs inside a folder:
function getAllDirs($directory, $directory_seperator) {
$dirs = array_map(function ($item) use ($directory_seperator) {
return $item . $directory_seperator;
}, array_filter(glob($directory . '*'), 'is_dir'));
foreach ($dirs AS $dir) {
$dirs = array_merge($dirs, getAllDirs($dir, $directory_seperator));
}
return $dirs;
}
function getAllImgs($directory) {
$resizedFilePath = array();
foreach ($directory AS $dir) {
foreach (glob($dir . '*.jpg') as $filename) {
array_push($resizedFilePath, $filename);
}
}
return $resizedFilePath;
}
$directory = "C:/xampp/htdocs/images/";
$directory_seperator = "/";
$allimages = getAllImgs(getAllDirs($directory, $directory_seperator));
Using balphp's scan_dir function:
https://github.com/balupton/balphp/blob/765ee3cfc4814ab05bf3b5512b62b8b984fe0369/lib/core/functions/_scan_dir.funcs.php
scan_dir($dirPath, array('pattern'=>'image'));
Will return an array of all files that are images in that path and all subdirectories, using a $path => $filename structure. To turn off scanning subdirectories, set the recurse option to false
Please use the following code to read images from the folder.
function readDataFromImageFolder() {
$imageFolderName = 14;
$base = dirname(__FILE__);
$dirname = $base.DS.'images'.DS.$imageFolderName.DS;
$files = array();
if (!file_exists($dirname)) {
echo "The directory $dirname not exists.".PHP_EOL;
exit;
} else {
echo "The directory $dirname exists.".PHP_EOL;
$dh = opendir( $dirname );
while (false !== ($filename = readdir($dh))) {
if ($filename === '.' || $filename === '..') continue;
$files[] = $dirname.$filename;
}
uploadImages( $files );
}
}
Please click here for detailed explanation.
http://www.pearlbells.co.uk/code-snippets/read-images-folder-php/
You can use OPP oriented DirectoryIterator class.
foreach (new DirectoryIterator(IMAGEPATH) as $fileInfo) {
// Removing dots
if($fileInfo->isDot()) {
continue;
}
// You have all necessary data in $fileInfo
echo $fileInfo->getFilename() . "<br>\n";
}
while (($file = readdir($handle)) !== false) {
if (
($file == '.')||
($file == '..')
) {
continue;
}
$newfile = str_replace(' ', '_', $file);
rename(IMAGEPATH . $file, IMAGEPATH . $newfile);
$directoryfiles[] = $newfile;
}