PHP recursive delete function - php

I wrote recursive PHP function for folder deletion. I wonder, how do I modify this function to delete all files and folders in webhosting, excluding given array of files and folder names (for ex. cgi-bin, .htaccess)?
BTW
to use this function to totally remove a directory calling like this
recursive_remove_directory('path/to/directory/to/delete');
to use this function to empty a directory calling like this:
recursive_remove_directory('path/to/full_directory',TRUE);
Now the function is
function recursive_remove_directory($directory, $empty=FALSE)
{
// if the path has a slash at the end we remove it here
if(substr($directory,-1) == '/')
{
$directory = substr($directory,0,-1);
}
// if the path is not valid or is not a directory ...
if(!file_exists($directory) || !is_dir($directory))
{
// ... we return false and exit the function
return FALSE;
// ... if the path is not readable
}elseif(!is_readable($directory))
{
// ... we return false and exit the function
return FALSE;
// ... else if the path is readable
}else{
// we open the directory
$handle = opendir($directory);
// and scan through the items inside
while (FALSE !== ($item = readdir($handle)))
{
// if the filepointer is not the current directory
// or the parent directory
if($item != '.' && $item != '..')
{
// we build the new path to delete
$path = $directory.'/'.$item;
// if the new path is a directory
if(is_dir($path))
{
// we call this function with the new path
recursive_remove_directory($path);
// if the new path is a file
}else{
// we remove the file
unlink($path);
}
}
}
// close the directory
closedir($handle);
// if the option to empty is not set to true
if($empty == FALSE)
{
// try to delete the now empty directory
if(!rmdir($directory))
{
// return false if not possible
return FALSE;
}
}
// return success
return TRUE;
}
}

Try something like this:
$it = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator('%yourBaseDir%'),
RecursiveIteratorIterator::CHILD_FIRST
);
$excludeDirsNames = array();
$excludeFileNames = array('.htaccess');
foreach($it as $entry) {
if ($entry->isDir()) {
if (!in_array($entry->getBasename(), $excludeDirsNames)) {
try {
rmdir($entry->getPathname());
}
catch (Exception $ex) {
// dir not empty
}
}
}
elseif (!in_array($entry->getFileName(), $excludeFileNames)) {
unlink($entry->getPathname());
}
}

I'm using this function to delete the folder with all files and subfolders:
function removedir($dir) {
if (substr($dir, strlen($dir) - 1, 1) != '/')
$dir .= '/';
if ($handle = opendir($dir)) {
while ($obj = readdir($handle)) {
if ($obj != '.' && $obj != '..') {
if (is_dir($dir . $obj)) {
if (!removedir($dir . $obj))
return false;
}
else if (is_file($dir . $obj)) {
if (!unlink($dir . $obj))
return false;
}
}
}
closedir($handle);
if (!#rmdir($dir))
return false;
return true;
}
return false;
}
$folder_to_delete = "folder"; // folder to be deleted
echo removedir($folder_to_delete) ? 'done' : 'not done';
Iirc I got this from php.net

You could provide an extra array parameter $exclusions to recursive_remove_directory(), but you'll have to pass this parameter every time recursively.
Make $exclusions global. This way it can be accessed in every level of recursion.

Related

copy entire directory but exclude some files php

trying to find a way to copy entire directory but exclude certain files, in this case just need to exclude a directory which will always contain just 1 file a png... figured could use something similar to this code but have absolutely no clue as to how to exclude a file only
function xcopy($source, $dest, $permissions = 0755)
{
// Check for symlinks
if (is_link($source)) {
return symlink(readlink($source), $dest);
}
// Simple copy for a file
if (is_file($source)) {
return copy($source, $dest);
}
// Make destination directory
if (!is_dir($dest)) {
mkdir($dest, $permissions);
}
// Loop through the folder
$dir = dir($source);
while (false !== $entry = $dir->read()) {
// Skip pointers
if ($entry == '.' || $entry == '..') {
continue;
}
// Deep copy directories
xcopy("$source/$entry", "$dest/$entry", $permissions);
}
// Clean up
$dir->close();
return true;
}
Here is a function that may work for you. I have notated for clarification:
<?php
function CopyDirectory($settings = false)
{
// The script may take some time if there are lots of files
ini_set("max_execution_time",3000);
// Just do some validation and pre-sets
$directory = (isset($settings['dir']) && !empty($settings['dir']))? $settings['dir'] : false;
$copyto = (isset($settings['dest']) && !empty($settings['dest']))? $settings['dest'] : false;
$filter = (isset($settings['filter']) && !empty($settings['filter']))? $settings['filter'] : false;
// Add the copy to destinations not to copy otherwise
// you will have an infinite loop of files being copied
$filter[] = $copyto;
// Stop if the directory is not set
if(!$directory)
return;
// Create a recursive directory iterator
$dir = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory),RecursiveIteratorIterator::CHILD_FIRST);
try{
foreach($dir as $file) {
$copydest = str_replace("//","/",$copyto."/".str_replace($_SERVER['DOCUMENT_ROOT'],"",$file));
$compare = rtrim($file,".");
if(is_dir($file)) {
if(!is_dir($copydest)) {
if(!in_array($compare,$filter)) {
if(isset($skip) && !preg_match("!".$skip."!",$file) || !isset($skip))
#mkdir($copydest,0755,true);
else
$record[] = $copydest;
}
else {
$skip = $compare;
}
}
}
elseif(is_file($file) && !in_array($file,$filter)) {
copy($file,$copydest);
}
else {
if($file != '.' && $file != '..')
$record[] = $copydest;
}
}
}
// This will catch errors in copying (like permission errors)
catch (Exception $e)
{
$error[] = $e;
}
}
// Copy from
$settings['dir'] = $_SERVER['DOCUMENT_ROOT'];
// Copy to
$settings['dest'] = $_SERVER['DOCUMENT_ROOT']."/tester";
// Files and folders to not include contents
$settings["filter"][] = $_SERVER['DOCUMENT_ROOT'].'/core.processor/';
$settings["filter"][] = $_SERVER['DOCUMENT_ROOT'].'/config.php';
$settings["filter"][] = $_SERVER['DOCUMENT_ROOT'].'/client_assets/images/';
// Create instance
CopyDirectory($settings);
?>

php function return blank value on return statement and print right on echo

i create this function for search resume file from directory, if resume is available then function return full path, problem is function return nothing if i use "return", if i use "echo" then it will print right path
function search_resume($resume,$dir="uploads/resumes")
{
$root = scandir($dir);
foreach($root as $value)
{
/* echo $value."<br/>"; */
if($value === '.' || $value === '..') {continue;}
if(is_file("$dir/$value"))
{
if($value==$resume)
{
$path="$dir/$value";
return $path;
}
}
else
{
search_resume($resume,"$dir/$value");
}
}
}
A very typical, basic problem with recursive functions: you need to return recursive calls as well, they're not going to return themselves.
...
else {
$path = search_resume($resume,"$dir/$value");
if ($path) {
return $path;
}
}

Codeigniter delete the directory and its contents

I am trying to make codeigniter delete a product image folder.
Furthermore, the delete function I am trying to make needs to delete also all of its contents, so empty or not, the folder gets deleted. I'm guessing, it would use a recursive type of deletion...I'm not so sure at all.
I have tried the below functions for deleting :
function delete_directory($path)
{
$path=base_url().'products/thumb/';
$this->load->helper("file"); // load the helper
delete_files($path, true); // delete all files/folders
//rmdir($dirname);
if(rmdir($path)){
echo 'deleted';die;}
else{
echo 'not';die; }
return true;
}
But it always returning not
Deleting directory content:
It will probably work, I have used
$this->load->helper('directory');
$this->load->helper("file");
$dir_fiels = directory_map('resources/captcha/');
$len = sizeOf($dir_fiels);
for($i=0; $i<$len;$i++){
unlink('resources/captcha/'.$dir_fiels[$i]);
}
create an helper. see below:-
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
if ( ! function_exists('remove_directory'))
{
function remove_directory($directory, $empty=FALSE)
{
if(substr($directory,-1) == '/') {
$directory = substr($directory,0,-1);
}
if(!file_exists($directory) || !is_dir($directory)) {
return FALSE;
} elseif(!is_readable($directory)) {
return FALSE;
} else {
$handle = opendir($directory);
while (FALSE !== ($item = readdir($handle)))
{
if($item != '.' && $item != '..') {
$path = $directory.'/'.$item;
if(is_dir($path)) {
remove_directory($path);
}else{
unlink($path);
}
}
}
closedir($handle);
if($empty == FALSE)
{
if(!rmdir($directory))
{
return FALSE;
}
}
return TRUE;
}
}
}
then load this helper in Your controller and call function remove_directory()
/* End of file recursive_helper.php */
/* Location: /application/helpers/recursive_helper.php */
Delete all files:
delete_files('./path/to/your/directory/');
Include sub-folder(s):
delete_files('./path/to/your/directory/', TRUE);

How-to Giving Loading bar during copy process in php

This is my script:
function copyr($source, $dest) {
// Simple copy for a file
if (is_file($source)) {
return copy($source, $dest);
}
// Make destination directory
if (!is_dir($dest)) {
mkdir($dest);
}
// If the source is a symlink
if (is_link($source)) {
$link_dest = readlink($source);
return symlink($link_dest, $dest);
}
// Loop through the folder
$dir = dir($source);
while (false !== $entry = $dir -> read()) {
// Skip pointers
if ($entry == '.' || $entry == '..') {
continue;
}
// Deep copy directories
if ($dest !== "$source/$entry") {
copyr("$source/$entry", "$dest/$entry");
}
}
// Clean up
$dir -> close();
return true;
}
And I call function like this:
<?php copyr("D:/ahmad","E:"); ?>
When I call the function copyr always loading pages long.
And how to display the loading bar when the copy process?

How to delete all files in all sub-folders except those whose filename is 'whatever.jpg' in PHP?

What's the fastest way to delete all files in all sub-folders except those whose filename is 'whatever.jpg' in PHP?
Why not use iterators? This is tested:
function run($baseDir, $notThis)
{
foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($baseDir), RecursiveIteratorIterator::LEAVES_ONLY) as $file) {
if ($file->isFile() && $file->getFilename() != $notThis) {
#unlink($file->getPathname());
}
}
}
run('/my/path/base', 'do_not_cancel_this_file.jpg');
This should be what youre looking for, $but is an array holding exceptions.
Not sure if its the fastest, but its the most common way for directory iteration.
function rm_rf_but ($what, $but)
{
if (!is_dir($what) && !in_array($what,$but))
#unlink($what);
else
{
if ($dh = opendir($what))
{
while(($item = readdir($dh)) !== false)
{
if (in_array($item, array_merge(array('.', '..'),$but)))
continue;
rm_rf_but($what.'/'.$item, $but);
}
}
#rmdir($what); // remove this if you dont want to delete the directory
}
}
Example use:
rm_rf_but('.', array('notme.jpg','imstayin.png'));
Untested:
function run($baseDir) {
$files = scandir("{$baseDir}/");
foreach($files as $file) {
$path = "{$badeDir}/{$file}";
if($file != '.' && $file != '..') {
if(is_dir($path)) {
run($path);
} elseif(is_file($path)) {
if(/* here goes you filtermagic */) {
unlink($path);
}
}
}
}
}
run('.');

Categories