Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using scandir() to find folders in a directory (PHP)

Tags:

directory

php

I am using this peice of code:

$target = 'extracted/' . $name[0];   $scan = scandir($target); 

To scan the directory of a folder which is used for zip uploads. I want to be able to find all the folders inside my $target folder so I can delete them and their contents, leaving only the files in the $target directory.

Once I have returned the contents of the folder, I don't know how to differentiate between the folders and the files to be able to delete the folders.

Also, I have been told that the rmdir() function can't delete folders which have content inside them, is there any way around this?

Thanks, Ben.

like image 816
Ben McRae Avatar asked Mar 03 '09 22:03

Ben McRae


People also ask

What does Scandir do in PHP?

The scandir() function in PHP is an inbuilt function that is used to return an array of files and directories of the specified directory. The scandir() function lists the files and directories which are present inside a specified path.

How do I get a list of files in a directory in PHP?

The scandir() function returns an array of files and directories of the specified directory.

What is __ DIR __ in PHP?

The __DIR__ can be used to obtain the current code working directory. It has been introduced in PHP beginning from version 5.3. It is similar to using dirname(__FILE__). Usually, it is used to include other files that is present in an included file.


2 Answers

To determine whether or not you have a folder or file use the functions is_dir() and is_file()

For example:

 $path = 'extracted/' . $name[0]; $results = scandir($path);  foreach ($results as $result) {     if ($result === '.' or $result === '..') continue;      if (is_dir($path . '/' . $result)) {         //code to use if directory     } } 
like image 176
travis-146 Avatar answered Oct 11 '22 16:10

travis-146


Better to use DirectoryIterator

$path = 'extracted'; // '.' for current foreach (new DirectoryIterator($path) as $file) {     if ($file->isDot()) continue;      if ($file->isDir()) {         print $file->getFilename() . '<br />';     } } 
like image 22
Dominic Avatar answered Oct 11 '22 17:10

Dominic