PHP File Handling: Delete File

Submitted by: 
Language: 

In our previous tutorial, we have seen how to write the file and read the file, and we also know how to open a file in an assortment of different ways. At this time we’re going to focus on how to destroy(delete) files. Deleting is too simple but we need to keep two things in mind.

1. Close the file – because we can’t delete the open files
2. Must have permission on the folder containing the file – we have to make sure that the directory is writable, we could create the file, so we have also to make sure that we could delete the file.

When you are navigating and viewing the contents of a directory, you can see all the files that exist in that directory because the operating system displays the list of filenames. And as a scenario, you can think of these filenames as links that join the files to the directory you are currently viewing. So if you unlink a file, it's causing the system to forget about the it or delete it.

The PHP unlink function is not about removing files, it’s about removing a file name. The unlink deletes a name and possibly the file in referring to.

If you have remember that we created a “hello.txt” file in our previous tutorial called “PHP File Handling: Accessing File”.

  1. <?php
  2.  
  3. $testfile = 'hello.txt';
  4. if($fh = fopen($testfile, 'w')){
  5. fclose($fh);
  6. }else{
  7. echo 'Could not open the file';
  8. }
  9.  
  10. ?>

Output:

At this time, to delete “hello.txt” file, let’s create a new PHP file located in the same directory called “deletefile.php” and add the following code performing an unlink function.

  1. <?php
  2. //this is like we unset variable. And this is simple as one line of code
  3. unlink('hello.txt');
  4.  
  5. ?>

And if you are going to check the file in the document root, it is already gone.

Remember:
In deleting a file using the unlink function, be sure that you are deleting the right file!


Add new comment

Filtered HTML

  • Web page addresses and e-mail addresses turn into links automatically.
  • You may insert videos with [video:URL]
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd> <table> <tr> <td> <th> <img> <h1> <h2> <h3> <iframe> [video]
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <asp>, <c>, <cpp>, <csharp>, <css>, <html4strict>, <java>, <javascript>, <mysql>, <php>, <python>, <sql>, <vb>, <vbnet>. The supported tag styles are: <foo>, [foo].
  • Lines and paragraphs break automatically.

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.