rmdir and then rename does not work windows file exists

Php, Divx, Apache, phpBB
Forum rules
Do not post any code that circumvents rules of any server. You are responsible for anything you use here.
Post Reply
darknkreepy3#
Site Admin
Posts: 247
Joined: Tue Oct 27, 2009 9:33 pm

rmdir and then rename does not work windows file exists

Post by darknkreepy3# »

So, php on windows does not have a return flag in php to let your program script know that a folder has been removed correctly so you may then rename another folder the same as the removed one.

example:

gallery/01/
gallery/02/
gallery/03/

now:

Code: Select all

<?php
rmdir("gallery/01/");
rename("gallery/02/","gallery/01/");
?>
if you check your error.log in the apache server, you will notice it complains that the folder you removed is still there when you try to rename 02 to 01, even though you did erase 01. It takes a few thousand microseconds (1/1,000,000) for the apache server to do its work in the backend. So, do this...

Code: Select all

<?php
rmdir("gallery/01/");
rename("gallery/02/","gallery/01/");
usleep(50000);
?>
usleep(microseconds) allows the computer to just wait a tiny bit and then rename the folder. I have found that it is much easier than making a new folder, deep copying it, and then flush and delete the old folder. Let the operating system do it's job. The best part? It is windows | linux | unix friendly too!

*****if you tried to delete a folder with it's contents (sub folders and files) still there, that is a no go. You have to recursively delete the folder and all of it's contents as well. Remember to closedir($***) when $*** is the name of each handle you open for each sub directory (recursive loops in your tree deletion loop).

Code: Select all

<?php
//-----
function delTree($path)
	{
	//closedir so that it can then be removed per loop
	//echo "<h4>delTree $path</h4>";
	$handle=opendir($path);
	//
	if($handle)
		{
		//
		while(false !== ($file=readdir($handle)))
			{
			//
			if($file!="."&&$file!="..")
				{
				$dirTest=$path."/".$file;
				//
				if(is_dir($dirTest))
					{
					delTree($dirTest);
					}
				else
					{
					unlink($path.$file);
					//echo "$path.$file<br />";
					}
				}
			}
		closedir($handle);
		}
	rmdir($path);
	}
//-----
delTree("gallery/01/");
rmdir("gallery/01/");
usleep(50000);//give the OS a chance to finish it's work, there's no return flag for rmdir, etc
rename("gallery/02/","gallery/01/");
?>
Post Reply