I am testing out the functions of directory handling. I have a fold/directory that contains the following:
0 File folder
false File folder
my_pictures File folder
MVI_3094 mov file
img01 jpeg image
etc...
I wrote the following code to traverse the directory and print out specific resutls
$handle = opendir("files/");
while(($entry = readdir($handle)) !== false)
{
if($entry == "." || $entry == "..")
{
continue;
}
if(is_dir($entry))
{
echo "Directory:$entry<br />";
}
}
My only problem is that the second "if" statement does not output the results of
echo "Directory:$entry<br />";
even though the entry is a directory. I have checked the entry manually with the "var_dump" function and it returns true as a directory.
Any suggestions would help
Try this and check. Just a try...
$handle = opendir("files/");
while(($entry = readdir($handle)) !== false)
{
if($entry == "." || $entry == "..")
{
continue;
}
elseif(is_dir("files/".$entry))
{
echo "Directory:$entry<br />";
}
}
$entry is relative... is_dir expects an absolute path.
Try:
if(is_dir("files/".$entry))
readdir() is just returning the filenames. Your code is therefore looking for the files in the current directory rather than the subdirectory.
This will just probe the basename of whatever directory entry:
is_dir($entry)
The opendir() result list will be relative to the directory you gave for reading. So you need to use:
is_dir("files/$entry")
Your problem is that in elseif(is_dir($entry)) {, entry is equal to some string like "file.txt" or "somedirectory", which isn't a path pointing to a file at all. It needs to be "files/file.txt".
Try this:
$dir = "files/";
$handle = opendir($dir);
while(($entry = readdir($handle)) !== false)
{
if($entry == "." || $entry == "..")
{
continue;
}
if(is_dir($dir.$entry))
{
echo "Directory:$entry<br />";
}
}
Try using the DirectoryIterator:
$iterator = new \DirectoryIterator(realpath('files/'));
foreach($iterator as $file){
if($file->isDot())
continue;
if($file->isDir())
printf('Directory: %s <br/>', $file->getRealPath());
}
Related
I've set up some PHP to delete a directory, it's contents, and any subdirectory and its contents... I'm new to PHP so I'm most definitely doing something WRONG or am doing something in the most inefficient way.
Looking for some references or suggestion on how to do this better...
By the way, this code works fine. Using PHP 5.3.8.
chmod($main_dir, 0755);
if ($handle = opendir($main_dir)) {
while (false !== ($entry = readdir($handle))) {
$absolute_path = $main_dir.'/'.$entry;
if ($entry != "." && $entry != "..") {
chmod($absolute_path, 0755);
unlink($absolute_path);
//check if any folders exist, then delete files within
if (file_exists($absolute_path) && is_dir($absolute_path)) {
if ($child_handle = opendir($absolute_path)) {
while (false !== ($child_entry = readdir($child_handle))) {
$child_absolute_path = $absolute_path.'/'.$child_entry;
if ($child_entry != "." && $child_entry != "..") {
chmod($child_absolute_path, 0755);
unlink($child_absolute_path);
}
}
closedir($child_handle);
}
}
rmdir($absolute_path);
}
}
closedir($handle);
}
rmdir($main_dir);
Any thoughts? Much appreciated!
Im using PHP 5.3.8
You can use RecursiveDirectoryIterator to list all files and folders then delete them. Please Note that you have to use RecursiveIteratorIterator::CHILD_FIRST so that the files are deleted before the folder.
$dir = __DIR__ . "/test";
$di = new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS);
$ri = new RecursiveIteratorIterator($di, RecursiveIteratorIterator::CHILD_FIRST);
foreach ( $ri as $file ) {
$file->isDir() ? rmdir($file) : unlink($file);
}
Suppose I have a directory look like:
ABC
|_ a1.txt
|_ a2.txt
|_ a3.txt
|_ a4.txt
|_ a5.txt
How can I use PHP to get these file names to an array, limited to a specific file extension and ignoring directories?
You can use the glob() function:
Example 01:
<?php
// read all files inside the given directory
// limited to a specific file extension
$files = glob("./ABC/*.txt");
?>
Example 02:
<?php
// perform actions for each file found
foreach (glob("./ABC/*.txt") as $filename) {
echo "$filename size " . filesize($filename) . "\n";
}
?>
Example 03: Using RecursiveIteratorIterator
<?php
foreach(new RecursiveIteratorIterator( new RecursiveDirectoryIterator("../")) as $file) {
if (strtolower(substr($file, -4)) == ".txt") {
echo $file;
}
}
?>
Try this:
if ($handle = opendir('.')) {
$files=array();
while (false !== ($file = readdir($handle))) {
if(is_file($file)){
$files[]=$file;
}
}
closedir($handle);
}
scandir lists files and directories inside the specified path.
Here is the most Efficient way based on this article's benchmarks:
function getAllFiles() {
$files = array();
$dir = opendir('/ABC/');
while (($currentFile = readdir($dir)) !== false) {
if (endsWith($currentFile, '.txt'))
$files[] = $currentFile;
}
closedir($dir);
return $files;
}
function endsWith($haystack, $needle) {
return substr($haystack, -strlen($needle)) == $needle;
}
just use the getAllFiles() function, and you can even modify it to take the folder path and/or the extensions needed, it is easy.
Aside from scandir (#miku), you might also find glob interesting for wildcard matching.
If your text files is all that you have inside of the folder, the simplest way is to use scandir, like this:
<?php
$arr=scandir('ABC/');
?>
If you have other files, you should use glob as in Lawrence's answer.
$dir = "your folder url"; //give only url, it shows all folder data
if (is_dir($dir)){
if ($dh = opendir($dir)){
while (($file = readdir($dh)) !== false){
if($file != '.' and $file != '..'){
echo $file .'<br>';
}
}
closedir($dh);
}
}
output:
xyz
abc
2017
motopress
I have a directory with a lot of files inside:
pic_1_79879879879879879.jpg
pic_1_89798798789798789.jpg
pic_1_45646545646545646.jpg
pic_2_12345678213145646.jpg
pic_3_78974565646465645.jpg
etc...
I need to list only the pic_1_ files. Any idea how I can do?
Thanks in advance.
Use the glob() function
foreach (glob("directory/pic_1_*") as $filename) {
echo "$filename";
}
Just change directory in the glob call to the proper path.
This does it all in one shot versus grabbing the list of files and then filtering them.
The opend dir function will help you
$dir ="your path here";
$filetoread ="pic_1_";
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false) {
if (strpos($file,$filetoread) !== false)
echo "filename: $file : filetype: " . filetype($dir . $file) . "\n";
}
closedir($dh);
}
}
good luck see php.net opendir
This is what glob() is for:
glob — Find pathnames matching a pattern
Example:
foreach (glob("pic_1*.jpg") as $file)
{
echo $file;
}
Use scandir to list all the files in a directory and then use preg_grep to get the list of files which match the pattern you are looking for.
This is one of the samples from the manual
http://nz.php.net/manual/en/function.readdir.php
<?php
if ($handle = opendir('.')) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
echo "$file\n";
}
}
closedir($handle);
}
?>
you can modify that code to test the filename to see if it starts with pic_1_
using something like this
if (substr($file, 0, 6) == 'pic_1_')
Manual reference for substr
http://nz.php.net/manual/en/function.substr.php
I am trying to make a function that scans a folder for subfolders and then returns
a numeric array with the names of those folders.
This is the code i use for testing. Once i get it to print out the folder names and not just "." and ".." for present and above folder all will be well, and I can finish the function.
<?php
function super_l_getthemes($dir="themes")
{
if ($handle = opendir($dir)) {
echo "Handle: {$handle}\n";
echo "Files:\n";
while (false !== ($file = readdir($handle))) {
echo "{$file}<br>";
}
closedir($handle);
}
?>
The above code works fine, and prints out all the contents of the folder: files, subfolders and the "." and ".."
but if i replace:
while (false !== ($file = readdir($handle))) {
echo "{$file}<br>";
}
with:
while (false !== ($file = readdir($handle))) {
if(file_exists($file) && is_dir($file)){echo "{$file}";}
}
The function only prints "." and ".." , not the two folder names that I'd like it to print.
Any help is appreciated.
You must provide the absolute path to file_exists, otherwise it will look for it in the current execution path.
while (false !== ($file = readdir($handle))) {
$file_path = $dir . DIRECTORY_SEPARATOR . $file;
if (file_exists($file_path) && is_dir($file_path)) {
echo "{$file}";
}
}
The problem with readdir is that it only reads the strings of the named entries inside of the directory.
For instance, if you had file "foo" inside of directory "/path/to/files/", when using readdir on "/path/to/files/", you would eventually come to the string "foo".
Normally this wouldn't be a problem if it were in the same directory as the current working directory of the script, but, since you are reading from an arbitrary director, when you are attempting to inspect the entry (file, directory, whatever), you are calling is_dir on the bare string "foo".
I would try prefixing the name you pull out using readdir with the path to the file.
if ($handle = opendir($dir)) {
echo "Handle: {$handle}\n";
echo "Files:\n";
while ($file = readdir($handle)) {
/*** make $file into an absolute path ***/
$absolute_path = $dir . '/' . $file;
/*** NOW try stat'ing it ***/
if (is_dir($absolute_path)) {
/* it's a directory; do stuff */
}
}
closedir($handle);
}
You need to use:
while (false !== ($file = readdir($handle))) {
if(file_exists($dir.'/'.$file) && is_dir($dir.'/'.$file)){echo "{$file}";}
}
See http://php.net/readdir
If you only want the directories of the starting folder, you can simply do:
glob('/some/path/to/search/in/*', GLOB_ONLYDIR);
which would given you only those foldernames in an array. If you want all directories below a given path, try SPL's RecursiveDirectoryIterator
$fileSystemIterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator('/some/path/to/look/in'),
RecursiveIteratorIterator::SELF_FIRST);
Iterators can be used with foreach:
$directories = array();
foreach($fileSystemIterator as $path => $fileSystemObject) {
if($fileSystemObject->isDir()) {
$directories[] = $path;
}
}
You will then have an array $directories with all directories under the given path.
$files = array();
foreach(new DirectoryIteraror('/path') as $file){
if($file->isDir() /* && !$file->isDot()*/) $files[] = $file->getFilename();
}
[edit: though you wanted to skip the dot, commented it out)
I don't think you need both file_exists and is_dir,
You just need the is_dir function. From the manual:
is_dir Returns TRUE if the filename exists and is a directory, FALSE otherwise.
Use this:
while (false !== ($file = readdir($handle))) {
if(is_dir($file)){echo "{$file}";}
}
is_dir will also check whether it's a relative path or an absolute path.
$directory = scandir($path);
foreach($directory as $a){
if(is_dir($path.$a.'/') && $a != '.' && $a != '..'){
echo $a.'<br/>';
}
}
With the path given as shown, it displays the folders present in the path.
I agree with nuqqsa's solution, however, I'd like to add something to it.
Instead of specifying the path, you can change the current directory instead.
For example,
// open directory handle
// ....
chdir($dir);
while (false !== ($file = readdir($handle)))
if(is_dir($file))
echo $file;
// close directory handle
hey guys im looking for a way to show all mp3 files in a directory
this is my code to get that :
if ($handle = opendir($dirPath)) {
while (false !== ($file = readdir($handle))) {
if ($file = ".mp3" && $file = "..") {
echo '
<track>
<location>'.$dirPath.$file.'</location>
<creator>'.$file.'</creator>
</track>
';
}
}
closedir($handle);
}
now i know that this script will only show mp3 files in parent directory , but i need to show all mp3 files in all directory inside parent directory
problem is this code cant show files inside sub directories !
That code won't work at all. As you are setting the $file variable to ".." the result will be a lot of xml containing $dirPath and "..".
This is what you are looking for :)
$it = new RecursiveDirectoryIterator('path/to/files/');
foreach (new RecursiveIteratorIterator($it) as $file)
{
echo $file->getPathname() . '<br />';
}
You'll have to make a recursive function to search for all the MP3s.
Also, you probably meant if ($file == ".mp3" && $file == "..") { instead of if ($file = ".mp3" && $file = "..") {, and after that's changed, you get a condition that's always false. What are you trying to do there?
like icktoofay said, you'll have to make a recursive function. also, your code has an error:
if ($file = ".mp3" && $file = "..") {
won't work (and if ($file == ".mp3" && $file == "..") { is wrong, too). that line should look like this:
if (substr($file,-4) == ".mp3" || $file == "..") {
if you want to show the ".." - else it's just like this:
if (substr($file,-4) == ".mp3") {