Delete folder in php - php

I am trying to delete a folder using this script :
function Delete($path)
{
if (is_dir($path) === true)
{
$files = array_diff(scandir($path), array('.', '..'));
foreach ($files as $file)
{
Delete(realpath($path) . '/' . $file);
}
return rmdir($path);
}
else if (is_file($path) === true)
{
return unlink($path);
}
return false;
}
Delete('tmp');
It works in my Xampp server, but not on my webserver. I have changed the permissions of the folder and of the file it contains to 0777. So it should be writable(or in this case erasable) but nothing happens. I have even tryied giving the absolute path of the folder as the parameter of the function, but still nothing.Any ideas?

Use this :
function delTree($dir)
{
$files = glob( $dir . '*', GLOB_MARK );
foreach( $files as $file
{
if( is_dir( $file ) )
delTree( $file );
else
#unlink( $file );
}
if( is_dir($dir) ) rmdir( $dir );
};

Does it return false? Or it returns true but doesn't actually remove?
Normally I'd just guess it's a permissions problem.
Try making a folder with mkdir from PHP so PHP is the owner (so to speak) and try to remove that with your function.
If it works, it's a permissions/owner issue.

You can Try this code
<?php
$files = glob('application/*'); foreach($files as $file){ if(is_file($file)) unlink($file); }
?>
Or,
function viewDir($path) {
return is_file($path) ?
#unlink($path) :
array_map(__FUNCTION__, glob($path.'/*')) == #rmdir($path);
}
$dir=$_SERVER["DOCUMENT_ROOT"]."/xxxx/xxxx";
echo $dir;
viewDir($dir);

May be some files are opened using php like fopen and that time it will not delete the folder or directory. I have faced the same issue when I tried to delete a file/folder

Try something like this.
<?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;
}
?>
Hope this helps.

Try this line of code to delete a folder or folder files
I hope this will help you
function deleteAll($str) {
if (is_file($str)) {
return unlink($str);
}
elseif (is_dir($str)) {
$scan = glob(rtrim($str,'/').'/*');
foreach($scan as $index=>$path) {
$this->deleteAll($path);
}
return #rmdir($str);
}
}

Related

Deleting a file from storage does not delete an image

I'm using Laravel 5.8 and I wanted to delete an image from storage directory.
Basically the images is placed at this dir:
/storage/app/public/laboratories/labs/21/pics
And I tried running this method:
public function removeAzPic($lab,$azpic)
{
$destinationPath = storage_path("laboratories/labs/$lab/pics/$azpic");
Storage::delete($destinationPath);
return redirect()->back();
}
But the problem is it does not delete the file from storage!
So what's going wrong here? How can I solve this issue?
You can add this function to the helper.php for to delete files/directories recursively:
Function will help you to delete files at the moment. If you want to delete directories change if ( is_dir($full) ) { to if ( is_file($full) ) {
public static function rrmdir($src = null) {
if(!is_dir($src)) return false;
$dir = opendir($src);
while(false !== ( $file = readdir($dir)) ) {
if (( $file != '.' ) && ( $file != '..' )) {
$full = $src . '/' . $file;
if ( is_dir($full) ) {
self::rrmdir($full);
} else {
#unlink($full);
}
}
}
closedir($dir);
rmdir($src);
return true;
}

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('.');

PHP recursive delete function

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.

Scanning folder for files instead of array

I have this code:
<?php
$allowed = array('file1', 'file2', 'file3');
if (in_array($_GET["url"], $allowed)) {
// You can include
} else {
// Error message and dont include
}
?>
But instead of writing all the filenames in the array, how can i do so that the files in for example my folder FILES/ is accepted an no other files. How to do that?
Use the file_exists function like this:
if (file_exists('FILES/'.basename($_GET["url"]))) {
// You can include
} else {
// Error message and dont include
}
Function to retrieve files in a folder:
<?
function fGetFilesInFolder($sFolder) {
$aFiles = array();
if(file_exists($sFolder)) {
if ($handle = opendir($sFolder)) {
while (false !== ($sFile = readdir($handle))) {
if ($sFile != "." && $sFile != "..") $aFiles[] = $sFile;
}
closedir($handle);
}
}
return $aFiles;
}
?>

index files from a folder with subfolders and store location and filename

Hi I am looking for help to write a short script which will locate all files in a folder (which has sub-folders) list the path and filename in two seperate values before submitting to a database.
Can anyone help?
i have a recursive function to delete a folder, you'd have to change it so instead of calling the ´unlink´ function you could save it in a variable or in a database..
public function deleteFolder($dirname) {
if (is_dir($dirname)){
$dir_handle = opendir($dirname);
}
if (!isset($dir_handle) || !$dir_handle){
return false;
}
while($file = readdir($dir_handle)) {
if ($file != "." && $file != "..") {
if (!is_dir($dirname."/".$file)){
//change this line
unlink($dirname."/".$file);
} else {
//recursive call
$this->deleteFolder($dirname.'/'.$file);
}
}
}
closedir($dir_handle);
//also change this one
rmdir($dirname);
return true;
}
hope this helps.. good luck!
<?php
print_r(getPathFiles("./"));
function getPathFiles($dir) {
$ite=new RecursiveDirectoryIterator($dir);
$foo=new RecursiveIteratorIterator($ite);
$ret=array();
foreach ($foo as $path=>$cur) {
$ret[]=array('dir'=>dirname($path),'file'=>basename($path));
}
return $ret;
}
?>

Categories