PHP: Delete or unlink a file on the server
PHP has the capacity to work with server-side files in many ways creating, opening, reading, and writing. When you are done with a file, it is a simple matter to delete it using a PHP script.
When a file is no longer needed on the server, as with temporary files, it can be deleted using the unlink() function. To delete a file referenced by the variable $tmpfile, use the following code:
$tmpfile = "/tmp/somefile.txt";
The unlink() function returns true if the file was successfully deleted and false if there was a problem.
If there is a problem, it is most likely because you do not have permission to delete the file. In the case of UNIX filesystems, unlinking a file requires write access to the directory containing the file, not to the file itself. If PHP created the file initially, then this is not an issue since the directory must be writable to create a file.
If this doesn’t seem reasonable, think about a directory as a file which contains the information about the contents of the directory. To delete a file, no changes are required to the file, but the directory containing the file must be altered to reflect the deletion. Therefore, only the directory must be writable by the user in order to remove the file.
Follow the reactions below and share your own thoughts.