Delete a file in PHP
This article demonstrates how to delete a file in PHP.
In PHP, you can use the unlink() function to delete a file from the file system. It works similarly to the Unix C unlink() function.
|
1 2 3 4 |
<?php $file = '/path/to/directory/file.txt'; unlink($file); ?> |
If the specified file is a symlink, the unlink() function deletes it. If the file does not exist, a PHP warning will be thrown. You might want to check if the file exists or not before calling the unlink() function. This can be done using the file_exists() function.
|
1 2 3 4 5 6 7 8 9 10 |
<?php $file = '/path/to/directory/file.txt'; if (file_exists($file)) { unlink($file); echo "File deleted successfully"; } else { echo "File not found"; } ?> |
Furthermore, if the file is a directory, the unlink() function will throw a PHP warning. It is advisable to check first whether the specified file is a directory or not. This can be done using the is_dir() function, which returns a boolean value depending on the result.
|
1 2 3 4 5 6 7 8 9 10 |
<?php $file = '/path/to/directory/file.txt'; if (file_exists($file) && !is_dir($file)) { unlink($file); echo "File deleted successfully"; } else { echo "File not found or it is a directory"; } ?> |
If you want to delete multiple files, you can do so within a loop. To illustrate, the following solution iterates over an array of filenamesand deletes each file individually using unlink().
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<?php $dir = '/path/to/directory'; $files = ['1.txt', '2.txt', '3.txt']; foreach ($files as $file) { if (file_exists("$dir/$file") && !is_dir("$dir/$file")) { unlink("$dir/$file"); } else { echo "File $file not found or it is a directory"; } } ?> |
That’s all there is to deleting a file in PHP.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)