note 123175 deleted from function.unlink by cmb
| From: | cmb@php.net | Date: | Sun, 29 Dec 2019 11:40:13 +0000 |
| Subject: | note 123175 deleted from function.unlink by cmb | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-213699@lists.php.net to get a copy of this message | ||
Note Submitter: muhammad dot begawala at gmail dot com
----
Handling "Resource Unavailable" error by unlink() as Exception using try catch
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
// '@' 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.
}