How to delete a file in PHP? Unlink php - deleting files How it all works.

We continue the lesson, which is dedicated to the topic “ Working with PHP Files" If you haven’t read the previous one, I recommend reading it, and for those who have read it, let’s move on. In this lesson you will learn how to delete a created or existing file using PHP, copy or rename, lock a file.
Well, if you are ready, then go to battle...

Deleting a file in PHP

If you need to delete any file, use the PHP unlink() function:

Unlink(filename);

Filename – here enter the name of the file you want to delete.

Let's say we need to delete the file “file.txt”, an example to fill would be like this:

Unlink("file.txt");

Ready code:



If the file "file.txt" was present, the script deleted it.

Copying a file in PHP

If you need to copy content from one file to another file, use the PHP copy() function.

Copy("file1", "file2");

File1 – file name from where the text will be copied
- file2 – file name where the text will be copied

For example, create a file called “file2.txt” on your local server in the “test-1” folder. Let the file be empty. Now let's paste this code copy("file.txt", "file2.txt"); in php code “file.php”:



What have we done? Created a file called “file.txt” via PHP, made an entry in the file “file.txt” via PHP “ I'm glad to see you on the blog site ", displayed the result in the browser, copied the text from the file "file.txt" and pasted it into the file "file2.txt". Don't believe that this happened? Do you remember that the file “file2.txt” was empty?! Open it! And what do you see? Yes, that's right, the text that was in the file “file.txt”:

Renaming a file in PHP

To rename a file, use the PHP rename() function:

Rename("file1", "file2");

File1 – the name of the file that needs to be replaced ( rename)
- file2 – here you need to give a new file name

Here's an example to fill in:

Rename("file2..txt");

Here is the finished code:



The file “file2.txt” has been renamed to the file “site.txt”.

This is where I think we should end our lesson. But that's not all, in the next lesson we will continue working with files.

In the previous article we talked about it, and there I introduced you to function rmdir(), which deletes the directory. However, I said that this way you can only delete an empty directory, but how to delete a directory with files, You will find out now.

The principle is very simple: to delete directory with files, you must first delete all files, as well as all subdirectories. There may also be files and other subdirectories inside subdirectories, these also need to be cleared. In general, the difficulty is that the depth of the directories can be very large. And it is obvious that recursion suggests itself - calling a function within itself.

Despite the apparent complexity of the algorithm, the implementation is very simple and transparent:

function removeDirectory($dir) (
if ($objs = glob($dir."/*")) (
foreach($objs as $obj) (
is_dir($obj) ? removeDirectory($obj) : unlink($obj);
}
}
rmdir($dir);
}
?>

I will try to explain in clear language the algorithm of this function. First of all, we get a list of all files inside a given directory. If they are not there, then delete it immediately. If they exist, then we begin to sort through them one by one. If the element is a file, then simply delete it ( unlink($obj)). If this is a directory, then we call our function again, passing this directory. This is recursion: the function calls itself. After the function calls itself, everything starts again, but with a different directory. All of its files are also deleted, and all of its directories are sent back to this function. When all directories and files are deleted, the already empty directory is deleted.

I’ll tell you this, this algorithm is not so useful from a practical point of view (it’s not so often necessary delete directories with files in PHP), how useful it is for the development of your thinking. This is a very simple algorithm and it solves a very, very complex problem. Therefore, learn to compose algorithms - this is the most important thing in any programming language.

8 years ago

Deleted a large file but seeing no increase in free space or decrease of disk usage? Using UNIX or other POSIX OS?

The unlink() is not about removing file, it"s about removing a file name. The manpage says: ``unlink - delete a name and possibly the file it refers to"".

Most of the time a file has just one name -- removing it will also remove (free, deallocate) the `body" of file (with one caveat, see below). That"s the simple, usual case.

However, it "s perfectly fine for a file to have several names (see the link() function), in the same or different directories. All the names will refer to the file body and `keep it alive", so to say. Only when all the names are removed, the body of file is actually freed.

The caveat:
A file"s body may *also* be `kept alive" (still using diskspace) by a process holding the file open. The body will not be deallocated (will not free disk space) as long as the process holds it open. In fact, there"s a fancy way of resurrecting a file removed by a mistake but still held open by a process...

10 years ago

I have been working on some little tryout where a backup file was created before modifying the main textfile. Then when an error is thrown, the main file will be deleted (unlinked) and the backup file is returned instead.

Though, I have been breaking my head for about an hour on why I couldn't get my permissions right to unlink the main file.

Finally I knew what was wrong: because I was working on the file and hadn’t yet closed the file, it was still in use and of course couldn’t be deleted:)

So I thought of mentoining this here, to avoid others of making the same mistake:

// First close the file
fclose($fp);

// Then unlink:)
unlink ($somefile);
?>

14 years ago

To delete all files of a particular extension, or in fact, delete all with wildcard, a much simple way is to use the glob function. Say I wanted to delete all jpgs.........

Foreach (glob ("*.jpg" ) as $filename ) (
echo " $filename size " . filesize ($filename) . "\n" ;
unlink ($filename);
}

?>

10 years ago

To anyone who"s had a problem with the permissions denied error, it"s sometimes caused when you try to delete a file that"s in a folder higher in the hierarchy to your working directory (i.e. when trying to delete a path that starts with "../").

So to work around this problem, you can use chdir() to change the working directory to the folder where the file you want to unlink is located.

$old = getcwd(); // Save the current directory
chdir($path_to_file);
unlink ($filename);
chdir ($old); // Restore the old working directory
?>

4 years ago

On OSX, when fighting against a "Permission Denied" error, make sure, the directory has WRITE permissions for the executing php-user.

Furthermore, if you rely on ACLs, and want to delete a file or symlink, the containing directory needs to have "delete_child" permission in order to unlink things inside. If you only grant "delete" to the folder that will allow you to delete the container folder itself, but not the objects inside.

4 years ago

This might seem obvious, but I was tearing my hair out with this problem - make sure the file you"re trying to delete isn"t currently being used. I had a script that was parsing a text file and was supposed to delete it after completing, but kept getting a permission denied error because I hadn't explicitly closed the file, hence it was technically still being "used" even though the parsing was complete.

11 years ago

Ggarciaa"s post above has already one small error, closedir has to be used even if $DeleteMe is false











}

Closedir($dh);
if ($DeleteMe )(
@rmdir($dir);
}
}

?>

9 months ago

Handling "Resource Unavailable" error by unlink() as Exception using try catch

Even is_file() or file_exists() will check for file is exists or not, there are chances that file is being used by some applications that will prevent deletion and unlink() will display "Resource Unavailable" error.

So after trying many methods like: `is_resource()`, `is_writable()`, `stream_get_meta_data()`...etc, I reached the only best way to handle error while *"deleting"* a file that is either * *not exists** or **is exists but being used by some application**

function delete_file($pFilename)
{
if (file_exists($pFilename)) (
// Added by muhammad.begawala
// "@" will stop displaying "Resource Unavailable" error because of file is open some where.
// "unlink($pFilename) !== true" will check if file is deleted successfully.
// Throwing exception so that we can handle error easily instead of displaying to users.
if(@unlink($pFilename) !== true)
throw new Exception("Could not delete file: " . $pFilename . " Please close all applications that are using it.");
}
return true;
}

/* === USAGE === */

try (
if(delete_file("hello_world.xlsx") === true)
echo "File Deleted";
}
catch (Exception $e) (
echo $e->getMessage(); // will print Exception message defined above.
}

11 years ago

Ggarciaa"s post above has one small error, it will ignore file and directory strings that are evaluated as false (ie. "0")

Fixed code is below (false !==)

// ggarciaa at gmail dot com (04-July-2007 01:57)
// I needed to empty a directory, but keeping it
// so I slightly modified the contribution from
// stefano at takys dot it (28-Dec-2005 11:57)
// A short but powerful recursive function
// that works also if the dirs contain hidden files
// $dir = the target directory
// $DeleteMe = if true delete also $dir, if false leave it alone

Function SureRemoveDir ($dir, $DeleteMe) (
if(! $dh = @ opendir ($dir )) return;
while (false !== ($obj = readdir ($dh ))) (
if($obj == "." || $obj == ".." ) continue;
if (!@ unlink ($dir . "/" . $obj )) SureRemoveDir ($dir . "/" . $obj , true );
}
if ($DeleteMe )(
closedir($dh);
@rmdir($dir);
}
}

//SureRemoveDir("EmptyMe", false);
//SureRemoveDir("RemoveMe", true);

?>

8 years ago

Unlink can fail after using ODBC commands on the file (on Windows).

Neithernordid the trick.

Onlyreleased the file such that it could be deleted afterwards ...

PHP is a programming language primarily used to create dynamic web pages. Just like any other programming language, PHP contains a lot of features, including many useful ones. For example, the ability to delete a file, which you can use in your scripts.

This tip will help you learn how delete file in PHP using the function unlink.

Step-by-step instruction:

To delete a file in PHP you can use the function unlink. Using a simple script as an example, let’s look at the work unlink:

  1. Create a text file in a text editor (vi/vim, nano, gedit or just standard Notepad).
  2. Type or simply copy the following code into it:$file="example.log";
    unlink($file);
    ?>
  3. Save (for example, under the name testunlink.php) and place the created script file on your test web server. In the same directory, create an example.log file with any content. This is what we will delete.
  4. Run the script by calling it in your browser, and when you look again in the directory, you will find that the example.log file is no longer there. Unlink did the trick!

How it all works:

The first line of script code: we determine the type of our script.

Second line of code: After running the script we created, the file variable will be assigned the value example.log(note that a file with the same name must be present in the same directory as the script we created. Just create it with any content!).

Third line of code: Delete the example.log file by passing it as an argument to the unlink function.

Fourth line of script code: end of php code.



 

It might be useful to read: