Delete file in php

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;
}
try {
    if( delete_file('file_name') === true ){
      echo 'File Deleted';
    }
       
}
catch (Exception $e) {
   echo $e->getMessage(); // will print Exception message defined above.
}
try {
    if( file_exists($f) === true  ){
      if( @unlink($f) !== true )
      throw new Exception('Could not delete file: ' . $f . ' Please close all applications that are using it.');
      //echo 'File Deleted';
    }
       
}
catch (Exception $e) {
   echo $e->getMessage(); // will print Exception message defined above.
}


Leave a Reply