Renaming and Removing Files in PHP

By: Andi, Stig and Derick  

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 )

Installing PHP with nginx-server under windows

PHP ./configure RESULTING IN [email protected]_2_2_3_... AND UNRESOLVED REFERENCES WITH ORACLE OCI8

PHP 5.1.4 INSTALLATION on Solaris 9 (Sparc)

Building PHP 5.x with Apache2 on SuSE Professional 9.1/9.2

Installing PHP 5.x with Apache 2.x on HP UX 11i and configuring PHP 5.x with Oracle 9i

Cannot load /usr/local/apache/libexec/libphp4.so into server: ld.so.1:......

Setting up PHP in Windows 2003 Server IIS7, and WinXP 64

error: "Service Unavailable" after installing PHP to a Windows XP x64 Pro

Running different websites on different versions of PHP in Windows 2003 & IIS6 platform

Function to convert strings to strict booleans in PHP

Convert IP address to integer and back to IP address in PHP

Function to return number of digits of an integer in PHP

Function to force strict boolean values in PHP

Function to sort array by elements and count of element in PHP

PHP pages does not display in IIS 6 with Windows 2003

Latest Articles (in PHP)

Comment on this tutorial