You can delete files from the server with PHP’s file system function unlink() which will delete or remove the files. It can remove all type of files like images, document, media files .. etc.It will return TRUE on success or FALSE on failure.If there is a problem, it is most likely because you do not have permission to delete the file.The directory must be writable by the user in order to remove the file.File not required write permissions.
I am gonna use is_readable() function which tells whether a file exists and is readable or not, It is better to check before attempting to delete action.
For example, if you want to delete files from upload folder(which is located at web server root folder).
1 2 3 4 5 6 7 8 9 |
<?php $file = "uploads/my_test_file.txt"; if (is_readable($file) && unlink($file)) { echo "The file has been deleted"; } else { echo "The file was not found or not readable and could not be deleted"; } |
That’s it.
I hope you like this Post, Please feel free to comment below, your suggestion and problems if you face - we are here to solve your problems.
I am Arjun from Hyderabad (India). I have been working as a software engineer from the last 7+ years, and it is my passion to learn new things and implement them as a practice. Aside from work, I like gardening and spending time with pets.
Thanks arjun 🙂
You are welcome!
still not working unlink()
Not working means?
I am updating information on item table and I want my previously stored image deleted when I update item’s image with new one. I am very new to CI and I don’t exactly know how to use unlink function and where to put it in my edit function?
Hold the previous image path in the variable and after uploading file to server, updating the entry in database delete it.
Thankyou for best solution it work for me.