I would like to list all .jpg files from folders and subfolders.
I have that simple code:
<?php
// directory
$directory = "img/*/";
// file type
$images = glob("" . $directory . "*.jpg");
foreach ($images as $image) {
echo $image."<br>";
}
?>
But that lists .jpg files from img folder and one down.
How to scan all subfolders?
Php coming with the DirectoryIterator which can be very useful in that case.
Please note that this simple function can be easly improved by adding the whole path to a file instead the only file name, and maybe use something else instead of the reference.
/*
* Find all file of the given type.
* #dir : A directory from which to start the search
* #ext : The extension. XXX : Dont call it with "." separator
* #store : A REFERENCE to an array on which store the element found.
* */
function allFileOfType($dir, $ext, &$store) {
foreach(new DirectoryIterator($dir) as $subItem) {
if ($subItem->isFile() && $subItem->getExtension() == $ext)
array_push($store, $subItem->getFileName());
elseif(!$subItem->isDot() && $subItem->isDir())
allFileOfType($subItem->getPathName(), $ext, $store);
}
}
$jpgStore = array();
allFileOfType(__DIR__, "jpg", $jpgStore);
print_r($jpgStore);
As a directotry can contain subdirectories, and in their turn contains subdirectories, so we should use a recursive function. glob() is here not sufficient. This might work for you:
<?php
function getDir4JpgR($directory) {
if ($handle = opendir($directory)) {
while (false !== ($entry = readdir($handle))) {
if($entry != "." && $entry != "..") {
$str1 = "$directory/$entry";
if(preg_match("/\.jpg$/i", $entry)) {
echo $str1 . "<br />\n";
} else {
if(is_dir($str1)) {
getDir4JpgR($str1);
}
}
}
}
closedir($handle);
}
}
//
// call the recursive function in the main block:
//
// directory
$directory = "img";
getDir4JpgR($directory);
?>
I put this into a file named listjpgr.php. And in my Chrome Browser, it gives this capture:
I am calling my php function from some other website which delete a folder on my server in background.
This is a function which I am using to delete a folder.
public static function remove($dir)
{
if (is_dir($dir)) {
$diropen = opendir($dir);
while($d = readdir($diropen)) {
if ($d!= '.' && $d != '..') {
self::remove($dir . "/$d");
}
}
#rmdir($dir);
} elseif (is_file($dir)) {
#unlink($dir);
}
}
If I am having three files in folder then it deletes only two and unable to delete last file or unlink fails on last file.
If I am having two files then it deletes only one file.
I have checked writable permission using is_writable it is true for all files.
Can somebody please help me out. or how to debug this behavior as this function is getting called in background.
my directory was open in some other function , so I closedir my folder and then above function working fine.
<?php
function delete_directory($target) {
if (is_dir($target))
$dir_handle = opendir($target);
if (!$dir_handle)
return false;
while($file = readdir($dir_handle)) {
if ($file != "." && $file != "..") {
if (!is_dir($dirname."/".$file))
unlink($dirname."/".$file);
else
delete_directory($target.'/'.$file);
}
}
closedir($dir_handle);
rmdir($target);
return true;
}
?>
use closedir and you'll be fine.
On my way to learning the mkdir(); function in PHP, I have created a folder on my server with a path like so
files/New\\\\
Now, I can not delete this for the life of me...
I found one other post that said I would need to use
rmdir();
and escape the backslashes with more backslashes...
Needless to say, I can not get this to work... I had no idea that PHP added slashes through a post. I know from here forth I should use stripslashes(); but for now, I am stuck with two non deletable folders.
Any ideas guys?
Quick'n'dirty script:
$filename = glob('../files/*');
foreach($filename as $file) {
print "'". $file. "' ";
if(strstr($file,'New')) {
if(is_file($file)) {
unlink($file);
}
}
}
foreach($filename as $file) {
if(strstr($file,'New')) {
r_rmdir($file);
}
}
function r_rmdir($dir) {
if (is_dir($dir)) {
$objects = scandir($dir);
foreach ($objects as $object) {
if ($object != "." && $object != "..") {
if (filetype($dir."/".$object) == "dir") r_rmdir($dir."/".$object); else unlink($dir."/".$object);
}
}
reset($objects);
rmdir($dir);
}
}
1.
This should remove all the folders and files you have created for both directories, just run this script and it should remove them both completely
PHP
rmdir("../files/New\\\\/thumbnail");
rmdir("../files/New\\\\");
$filename = glob('../files/New\\\\\\\\\\\\\\\\/*');
foreach($filename as $file) {
if(is_file($file)) {
unlink($file);
}
}
rmdir("../files/New\\\\\\\\\\\\\\\\/thumbnail");
rmdir("../files/New\\\\\\\\\\\\\\\\");
2.
Have you tried renaming the folder with php? Like, so
PHP
$oldname = '../files/New\\\\';
$newname = '../files/please';
rename($oldname, $newname);
I have a script (got it from somewhere here in StackOverflow, credits don't go to me!) to
delete a folder + its contents. However, it's not working for me. After deleting the folder a record from my DB should be erased and this happens just fine. However, the folder doesn't get deleted and neither its contents! This is my code:
<?php
$filepath = dirname(__FILE__);
$gemeented = preg_replace( '#^(.*)/(.*?)/(.*?)/(.*?)/(.*?)/(.*?)$#', "$2", $filepath );
$plaatsd = preg_replace( '#^(.*)/(.*?)/(.*?)/(.*?)/(.*?)/(.*?)$#', "$4", $filepath );
$hrubriekd = preg_replace( '#^(.*)/(.*?)/(.*?)/(.*?)/(.*?)/(.*?)$#', "$5", $filepath );
$bedrijfn = preg_replace( '#^(.*)/(.*?)/(.*?)/(.*?)/(.*?)/(.*?)$#', "$6", $filepath );
$filepath2 = "http://".$gemeented.".url.nl/".$plaatsd."/".$hrubriekd."/".$bedrijfn."/";
$filepath3 = "http://".$gemeented.".url.nl/".$plaatsd."/".$bedrijfn."/";
echo $filepath2;
function Delete($filepath2)
{
if (is_dir($filepath2) === true)
{
$files = array_diff(scandir($filepath2), array('.', '..'));
foreach ($files as $file)
{
Delete(realpath($filepath2) . '/' . $file);
}
return rmdir($filepath2);
}
else if (is_file($filepath2) === true)
{
return unlink($filepath2);
}
return false;
}
?>
To make sure my $filepath2 is correct I echoed it, the result is:
http://dongen.mydomain.nl/s-gravenmoer/aandrijvingenenbesturingen/bedrijfsnaam/
That's exactly the folder I want gone, however, it ain't happening! Folder has CHMOD 755.
EDIT:
Just using $filepath won't work either, echo-ing that gives me:
/vhosts/mydomain.nl/subdomains/dongen/httpdocs/s-gravenmoer/aandrijvingenenbesturingen/bedrijfsnaam
I wasn't able to get the above script working, but I managed to find another script which works for me! Just enter the relative path and that's it!
$dirname = "../".$bedrijfn."/";
delete_directory($dirname);
function delete_directory($dirname) {
if (is_dir($dirname))
$dir_handle = opendir($dirname);
if (!$dir_handle)
return false;
while($file = readdir($dir_handle)) {
if ($file != "." && $file != "..") {
if (!is_dir($dirname."/".$file))
unlink($dirname."/".$file);
else
delete_directory($dirname.'/'.$file);
}
}
closedir($dir_handle);
rmdir($dirname);
return true;
}
Hope it helps somebody out!
Sander
You can't use url to delete files, you should give unlink a filesystem path.
(Edit: the same goes for rmdir)
For example I had a folder called `Temp' and I wanted to delete or flush all files from this folder using PHP. Could I do this?
$files = glob('path/to/temp/*'); // get all file names
foreach($files as $file){ // iterate files
if(is_file($file)) {
unlink($file); // delete file
}
}
If you want to remove 'hidden' files like .htaccess, you have to use
$files = glob('path/to/temp/{,.}*', GLOB_BRACE);
If you want to delete everything from folder (including subfolders) use this combination of array_map, unlink and glob:
array_map( 'unlink', array_filter((array) glob("path/to/temp/*") ) );
This call can also handle empty directories ( thanks for the tip, #mojuba!)
Here is a more modern approach using the Standard PHP Library (SPL).
$dir = "path/to/directory";
if(file_exists($dir)){
$di = new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS);
$ri = new RecursiveIteratorIterator($di, RecursiveIteratorIterator::CHILD_FIRST);
foreach ( $ri as $file ) {
$file->isDir() ? rmdir($file) : unlink($file);
}
}
foreach (new DirectoryIterator('/path/to/directory') as $fileInfo) {
if(!$fileInfo->isDot()) {
unlink($fileInfo->getPathname());
}
}
This code from http://php.net/unlink:
/**
* Delete a file or recursively delete a directory
*
* #param string $str Path to file or directory
*/
function recursiveDelete($str) {
if (is_file($str)) {
return #unlink($str);
}
elseif (is_dir($str)) {
$scan = glob(rtrim($str,'/').'/*');
foreach($scan as $index=>$path) {
recursiveDelete($path);
}
return #rmdir($str);
}
}
$dir = 'your/directory/';
foreach(glob($dir.'*.*') as $v){
unlink($v);
}
Assuming you have a folder with A LOT of files reading them all and then deleting in two steps is not that performing.
I believe the most performing way to delete files is to just use a system command.
For example on linux I use :
exec('rm -f '. $absolutePathToFolder .'*');
Or this if you want recursive deletion without the need to write a recursive function
exec('rm -f -r '. $absolutePathToFolder .'*');
the same exact commands exists for any OS supported by PHP.
Keep in mind this is a PERFORMING way of deleting files. $absolutePathToFolder MUST be checked and secured before running this code and permissions must be granted.
See readdir and unlink.
<?php
if ($handle = opendir('/path/to/files'))
{
echo "Directory handle: $handle\n";
echo "Files:\n";
while (false !== ($file = readdir($handle)))
{
if( is_file($file) )
{
unlink($file);
}
}
closedir($handle);
}
?>
The simple and best way to delete all files from a folder in PHP
$files = glob('my_folder/*'); //get all file names
foreach($files as $file){
if(is_file($file))
unlink($file); //delete file
}
Got this source code from here - http://www.codexworld.com/delete-all-files-from-folder-using-php/
unlinkr function recursively deletes all the folders and files in given path by making sure it doesn't delete the script itself.
function unlinkr($dir, $pattern = "*") {
// find all files and folders matching pattern
$files = glob($dir . "/$pattern");
//interate thorugh the files and folders
foreach($files as $file){
//if it is a directory then re-call unlinkr function to delete files inside this directory
if (is_dir($file) and !in_array($file, array('..', '.'))) {
echo "<p>opening directory $file </p>";
unlinkr($file, $pattern);
//remove the directory itself
echo "<p> deleting directory $file </p>";
rmdir($file);
} else if(is_file($file) and ($file != __FILE__)) {
// make sure you don't delete the current script
echo "<p>deleting file $file </p>";
unlink($file);
}
}
}
if you want to delete all files and folders where you place this script then call it as following
//get current working directory
$dir = getcwd();
unlinkr($dir);
if you want to just delete just php files then call it as following
unlinkr($dir, "*.php");
you can use any other path to delete the files as well
unlinkr("/home/user/temp");
This will delete all files in home/user/temp directory.
Another solution:
This Class delete all files, subdirectories and files in the sub directories.
class Your_Class_Name {
/**
* #see http://php.net/manual/de/function.array-map.php
* #see http://www.php.net/manual/en/function.rmdir.php
* #see http://www.php.net/manual/en/function.glob.php
* #see http://php.net/manual/de/function.unlink.php
* #param string $path
*/
public function delete($path) {
if (is_dir($path)) {
array_map(function($value) {
$this->delete($value);
rmdir($value);
},glob($path . '/*', GLOB_ONLYDIR));
array_map('unlink', glob($path."/*"));
}
}
}
Posted a general purpose file and folder handling class for copy, move, delete, calculate size, etc., that can handle a single file or a set of folders.
https://gist.github.com/4689551
To use:
To copy (or move) a single file or a set of folders/files:
$files = new Files();
$results = $files->copyOrMove('source/folder/optional-file', 'target/path', 'target-file-name-for-single-file.only', 'copy');
Delete a single file or all files and folders in a path:
$files = new Files();
$results = $files->delete('source/folder/optional-file.name');
Calculate the size of a single file or a set of files in a set of folders:
$files = new Files();
$results = $files->calculateSize('source/folder/optional-file.name');
<?
//delete all files from folder & sub folders
function listFolderFiles($dir)
{
$ffs = scandir($dir);
echo '<ol>';
foreach ($ffs as $ff) {
if ($ff != '.' && $ff != '..') {
if (file_exists("$dir/$ff")) {
unlink("$dir/$ff");
}
echo '<li>' . $ff;
if (is_dir($dir . '/' . $ff)) {
listFolderFiles($dir . '/' . $ff);
}
echo '</li>';
}
}
echo '</ol>';
}
$arr = array(
"folder1",
"folder2"
);
for ($x = 0; $x < count($arr); $x++) {
$mm = $arr[$x];
listFolderFiles($mm);
}
//end
?>
For me, the solution with readdir was best and worked like a charm. With glob, the function was failing with some scenarios.
// Remove a directory recursively
function removeDirectory($dirPath) {
if (! is_dir($dirPath)) {
return false;
}
if (substr($dirPath, strlen($dirPath) - 1, 1) != '/') {
$dirPath .= '/';
}
if ($handle = opendir($dirPath)) {
while (false !== ($sub = readdir($handle))) {
if ($sub != "." && $sub != ".." && $sub != "Thumb.db") {
$file = $dirPath . $sub;
if (is_dir($file)) {
removeDirectory($file);
} else {
unlink($file);
}
}
}
closedir($handle);
}
rmdir($dirPath);
}
public static function recursiveDelete($dir)
{
foreach (new \DirectoryIterator($dir) as $fileInfo) {
if (!$fileInfo->isDot()) {
if ($fileInfo->isDir()) {
recursiveDelete($fileInfo->getPathname());
} else {
unlink($fileInfo->getPathname());
}
}
}
rmdir($dir);
}
I've built a really simple package called "Pusheh". Using it, you can clear a directory or remove a directory completely (Github link). It's available on Packagist, also.
For instance, if you want to clear Temp directory, you can do:
Pusheh::clearDir("Temp");
// Or you can remove the directory completely
Pusheh::removeDirRecursively("Temp");
If you're interested, see the wiki.
I updated the answer of #Stichoza to remove files through subfolders.
function glob_recursive($pattern, $flags = 0) {
$fileList = glob($pattern, $flags);
foreach (glob(dirname($pattern).'/*', GLOB_ONLYDIR|GLOB_NOSORT) as $dir) {
$subPattern = $dir.'/'.basename($pattern);
$subFileList = glob_recursive($subPattern, $flags);
$fileList = array_merge($fileList, $subFileList);
}
return $fileList;
}
function glob_recursive_unlink($pattern, $flags = 0) {
array_map('unlink', glob_recursive($pattern, $flags));
}
This is a simple way and good solution. try this code.
array_map('unlink', array_filter((array) array_merge(glob("folder_name/*"))));