Note that there are some explanatory texts on larger screens.

plurals
  1. POPHP mkdir not working after rmdir
    text
    copied!<p>I have a chunk of code that tests if a directory exists, deletes it if it exists, and creates a new directory over it. It should be fairly simple.</p> <pre><code>if(is_dir($directory)){ $files = new RecursiveIteratorIterator( new RecursiveDirectoryIterator($directory,RecursiveDirectoryIterator::SKIP_DOTS), RecursiveIteratorIterator::CHILD_FIRST ); foreach($files as $fileinfo){ $todo = ($fileinfo-&gt;isDir() ? 'rmdir' : 'unlink'); $todo($fileinfo-&gt;getRealPath()); } rmdir($directory); //var_dump(is_dir($directory)); } clearstatcache(); mkdir($directory,0744); </code></pre> <p>If the directory does not exist yet, the <code>mkdir()</code> works just fine. But if the directory does exist, the <code>rmdir()</code> loop does its job, but PHP throws an error:</p> <pre><code>PHP Error[2]: mkdir(): Permission Denied </code></pre> <p>The commented <code>var_dump()</code> line shows me that PHP still thinks <code>$directory</code> is a directory even after the <code>rmdir()</code> call. So I use <code>clearstatcache()</code> to update it, but it still won't detect that the directory has been deleted. And when I look it up in the file system, the directory has in fact been deleted.</p> <p>If I run the script again (while the directory is gone), it works just fine.</p> <p>Can anyone figure out how to resolve this error? If it makes a difference, I am running this as a PHP command line script on my Win7/XAMPP dev environment.</p> <p>edit:</p> <p>Thanks to Wee Kiat and Phillip for the answer. The solution was to use <code>unset($files)</code> before <code>rmdir()</code> to close the recursive iterator, which was still keeping <code>$directory</code> open and causing <code>mkdir()</code> to choke. See their code below.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload