I have been working on a project that involves a step, during which the script needs to automatically remove a certain directory in Linux ( and all its contents ).
I am currently using the following code to do that:
# Perform a recursive removal of the obsolete folder
$dir_to_erase = $_SESSION['path'];
function removeDirectory($dir_to_erase) {
$files = glob($dir_to_erase . '/*');
foreach ($files as $file) {
is_dir($file) ? removeDirectory($file) : unlink($file);
}
rmdir($dir_to_erase);
return;
}
Where $_SESSION['path'] is the folder to erase. Been working like a charm, but I recently had to add a .htaccess file to the folder, and I noticed the script stopped working correctly ( it keeps removing the rest of the files fine, but not the .htaccess files ).
Can anyone point me as to what I should add to the code include the hidden dot files in the removal process?
simply, you can rely on DirectoryIterator
The DirectoryIterator class provides a simple interface for viewing
the contents of filesystem directories.
function removeDirectory($dir_to_erase) {
$files = new DirectoryIterator($dir_to_erase);
foreach ($files as $file) {
// check if not . or ..
if (!$file->isDot()) {
$file->isDir() ? removeDirectory($file->getPathname()) : unlink($file->getPathname());
}
}
rmdir($dir_to_erase);
return;
}
there are lot of features there you may make use of them, as check the owner which is pretty useful to make sure not to remove critical file.
You can slightly modify your function to remove hidden files also:
function removeDirectory($dir)
{
if (is_dir($dir)) {
$objects = scandir($dir);
foreach ($objects as $object) {
if ($object != "." && $object != "..") {
if (is_dir($dir."/".$object))
removeDirectory($dir."/".$object);
else
unlink($dir."/".$object);
}
}
rmdir($dir);
}
}
As per this answer:
PHP glob() doesnt find .htaccess
glob(".*") will find .htaccess
Related
I'm using rmdir() within PHP on Windows to recursively delete a folder structure. It deletes all the contents of the folder fine, but leaves the base folder in an "unaccessible" state. I still have to delete that folder manually, even though the system says it can't be found. Somehow the act of "deleting" reminds the OS that it needs to actually remove it.
Here's my code with sources commented in:
function rrmdir($dir)
{
// Taken from:
// https://stackoverflow.com/a/3338133/6674014
if(is_dir($dir))
{
$objects = scandir($dir);
foreach($objects as $object)
{
if($object != "." && $object != "..")
{
if(is_dir($dir."/".$object))
$this->rrmdir($dir."/".$object);
else
{
// Added modification from comment attached to:
// https://stackoverflow.com/a/12148318/6674014
$objPath = $dir.'/'.$object;
chmod($objPath, 999);
unlink($objPath);
}
}
}
rmdir($dir);
}
}
I've also used the $handle method, as well as the Folder Iterator Thing. These have also not worked.
And here's the error when I double-click the ghost folder:
How can this problem be fixed? Is it my code or OS that's messing up?
I'm trying to create a function which will run periodically to delete any old "user" folders which don't have an active user. This is the function I have:
function delete_temp_user_files() {
$dir = $_SERVER['DOCUMENT_ROOT'] . "/users/";
$dir_files = array();
$dir_files = scandir($dir);
foreach ($dir_files as $username) {
if ($username == "." || $username == "..") continue;
if (!user_exist($username)) {
$dir1 = $_SERVER['DOCUMENT_ROOT'] . "/users/" . $username;
if (!is_dir($dir1)) continue;
if (file_exists($dir1)) unlink($dir1);
}
}
}
But when it tries to delete the directory I get the error "Warning: unlink(/path/to/users/delete1/): Is a directory in /page.php on line..." I know the directory exists because I can see it in the directory, and it found it using scandir() anyway.
I use unlink to delete these same folders in other scripts and it works fine. The directories aren't empty so I can't user rmdir().
I'm not familiar with permissions or anything like that, is this some kind of issue with that? And do I need to worry about permissions if I only ever use PHP scripts to delete files and folders (like when the user clicks on the delete button which runs the script I wrote)?
UPDATE:
After scouring the web I finally found how to delete a directory and it's not easy lol Add this function into the previous function and it works!
function delete_dir($directory) {
foreach(glob("{$directory}/*") as $file)
{
if(is_dir($file)) {
delete_dir($file);
} else {
unlink($file);
}
}
rmdir($directory);
}
unlink is used to delete files, use rmdir
Please note, you must first delete all files in directory.
Also, your code is very dangerous. Assume with time, you have 100,000 users so will have 100,000 folders. Can you imagine how much time will this line take?
foreach ($dir_files as $username) {
Please think alternate way.
Good way, don't delete users from your database. find users who didn't login since 6 months (say) and disable them. this way, your loop is smaller.
There is a function given on the rmdir documentation page :
function rrmdir($dir) {
if (is_dir($dir)) {
$objects = scandir($dir);
foreach ($objects as $object) {
if ($object != "." && $object != "..") {
if (filetype($dir."/".$object) == "dir") rrmdir($dir."/".$object); else unlink($dir."/".$object);
}
}
reset($objects);
rmdir($dir);
}
}
Sure it will make your life easier.
I know that this is a late answer, but I solved it by checking if the file exists or not.
I'm using database for the path of the file. So you may try an example code below.
if(!empty($course->picture)){
// unlink here
}
I have some problem with making a script move picture/files from one folder to another.
I put the code belw
Can somebody help me to see what im doing wrong?
Grateful for any tip that i'll have.
<?PHP
chdir( dirname( __FILE__ ) );
include '../../bootstrap.php';
config( 'website.config' );
config( 'website.countries' );
import( 'system.cli' );
class adeleflytte extends Script {
Public function Main(){
// Get array of all source files
$files = scandir("pictures");
// Identify directories
$source = "pictures";
$destination = "/movedpictures";
// Cycle through all source files
foreach ($files as $file) {
if (in_array($file, array(".",".."))) continue;
// If we copied this successfully, mark it for deletion
if (copy($source.$file, $destination.$file)) {
$delete[] = $source.$file;
}
}
// Delete all successfully-copied files
foreach ($delete as $file) {
unlink($file);
}
}
}
CLI::Execute();
?>
rename function does this
rename
rename('image1.jpg', 'del/image1.jpg');
I think that the best way to move a file is to use a native function:
http://www.php.net/rename
As a parameters it accepts also full path, so it does move files as you need it.
Outputting what you're trying to copy is useful and would help track down the issue:
copy($source.$file, $destination.$file)
In this case since source is 'pictures' and $file is, say, 'pic.jpg' you are trying to copy
picturespic.jpg
You need to add / between these.
Additionally your destination /movedpictures is in the root directory of the filesystem which is likely not what you intended.
Suppose there's a directory in which there are numerous sub-directories. Now how can I scan all the subdirectories to find a file with name, say, abc.php and delete this file wherever its is found.
I tried doing something like this -
$oAllSubDirectories = scandir(getcwd());
foreach ($oAllSubDirectories as $oSubDirectory)
{
//Delete code here
}
But this code doesn't check directories inside the subdirectories. Any idea how can I do this ?
In general, you put the code inside a function and make it recursive: when it encounters a directory it calls itself in order to process its contents. Something like this:
function processDirectoryTree($path) {
foreach (scandir($path) as $file) {
$thisPath = $path.DIRECTORY_SEPARATOR.$file;
if (is_dir($thisPath) && trim($thisPath, '.') !== '') {
// it's a directory, call ourself recursively
processDirectoryTree($thisPath);
}
else {
// it's a file, do whatever you want with it
}
}
}
In this particular case you don't need to do that because PHP offers the ready-made RecursiveDirectoryIterator that does this automatically:
$it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator(getcdw()));
while($it->valid()) {
if ($it->getFilename() == 'abc.php') {
unlink($it->getPathname());
}
$it->next();
}
Im trying to Delete ALL Text files from a directory using a php script.
Here is what I have tried.....
<?php array_map('unlink', glob("/paste/*.txt")); ?>
I dont get an Error when I run this, yet It doesnt do the job.
Is there a snippet for this? Im not sure what else to try.
Your Implementation works all you need to do is use Use full PATH
Example
$fullPath = __DIR__ . "/test/" ;
array_map('unlink', glob( "$fullPath*.log"))
I expanded the submitted answers a little bit so that you can flexibly and recursively unlink text files located underneath as it's often the case.
// #param string Target directory
// #param string Target file extension
// #return boolean True on success, False on failure
function unlink_recursive($dir_name, $ext) {
// Exit if there's no such directory
if (!file_exists($dir_name)) {
return false;
}
// Open the target directory
$dir_handle = dir($dir_name);
// Take entries in the directory one at a time
while (false !== ($entry = $dir_handle->read())) {
if ($entry == '.' || $entry == '..') {
continue;
}
$abs_name = "$dir_name/$entry";
if (is_file($abs_name) && preg_match("/^.+\.$ext$/", $entry)) {
if (unlink($abs_name)) {
continue;
}
return false;
}
// Recurse on the children if the current entry happens to be a "directory"
if (is_dir($abs_name) || is_link($abs_name)) {
unlink_recursive($abs_name, $ext);
}
}
$dir_handle->close();
return true;
}
You could modify the method below but be careful. Make sure you have permissions to delete files. If all else fails, send an exec command and let linux do it
static function getFiles($directory) {
$looper = new RecursiveDirectoryIterator($directory);
foreach (new RecursiveIteratorIterator($looper) as $filename => $cur) {
$ext = trim($cur->getExtension());
if($ext=="txt"){
// remove file:
}
}
return $out;
}
i have modified submitted answers and made my own version,
in which i have made function which will iterate recursively in current directory and its all child level directories,
and it will unlink all the files with extension of .txt or whatever .[extension] you want to remove from all the directories, sub-directories and its all child level directories.
i have used :
glob() From the php doc:
The glob() function searches for all the pathnames matching pattern
according to the rules used by the libc glob() function, which is
similar to the rules used by common shells.
i have used GLOB_ONLYDIR flag because it will iterate through only directories, so it will be easier to get only directories and unlink the desired files from that directory.
<?php
//extension of files you want to remove.
$remove_ext = 'txt';
//remove desired extension files in current directory
array_map('unlink', glob("./*.$remove_ext"));
// below function will remove desired extensions files from all the directories recursively.
function removeRecursive($directory, $ext) {
array_map('unlink', glob("$directory/*.$ext"));
foreach (glob("$directory/*",GLOB_ONLYDIR) as $dir) {
removeRecursive($dir, $ext);
}
return true;
}
//traverse through all the directories in current directory
foreach (glob('./*',GLOB_ONLYDIR) as $dir) {
removeRecursive($dir, $remove_ext);
}
?>
For anyone who wonder how to delete (for example: All PDF files under public directory) you can do this:
array_map('unlink', glob( public_path('*.pdf')));