Renaming and Removing Files in PHP

By: Andi, Stig and Derick Viewed: 153217 times  Printer Friendly Format    


PHP provides the unlink() function for deleting a file, which “unlinks” the file from a directory. On a UNIX-like system the file will only be deleted if no programs have this file in use. This means that with the following script, the bytes associated with the file will only be released to the operating system after the fclose() is executed:

<?php

$f = fopen("testfile", "w");

unlink("testfile");

sleep(60);

fclose($f);

?>

During execution, you will not see the file in the directory anymore after unlink() is run. But, lsof still shows the file as being in use, and you can still read from it and write to it:

$ sudo lsof | grep testfile

php 14795 derick 3w REG 3,10 0 39636 /unlink/testfile (deleted)

Moving a file in PHP with the rename() function is atomic if you move/ rename the file to a place which is on the same file system. Atomic means that nothing can interfere with this, and that it is always guaranteed not to be interrupted. In case you want to move a file to a different file system, it is safer to do it in two steps, like this:

<?php

rename('/partition1/file.txt', '/partition2/.file.txt.tmp');

rename('/partition2/.file.txt.tmp', '/partition2/file.txt');

?>

The renaming is still not atomic, but the file in the new location will never be there partially, because the renaming from .file.txt.tmp to file.txt is atomic as the rename is on the same file system.



Most Viewed Articles (in PHP )

Latest Articles (in PHP)

Comment on this tutorial