Well, I have been wondering if I can handle the unlink() function properly. I dont want the unlink() function to throw some nasty error if it is un
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@gmail.com
// '@' 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.
}