0

I'm using Sentry for monitoring errors on a website. I have a piece of code that gives me trouble, it is from an old Kohana (PHP framework) module.

Giving this code (which I edited):

if ($delete === TRUE)
{
    $file_tmp = $file->getRealPath();
    clearstatcache(TRUE, $file_tmp);
    if (file_exists($file_tmp))
    {
        return @unlink($file_tmp);
    }
    return FALSE;
}

How can I make it so it doesn't trigger errors like this on Sentry:

Warning: unlink(/var/www/my-hostname-files/application/cache/25/2530cfe0309c86c52f8dda53ca493f4cf72fdbd3.cache): No such file or directory

The original code was just the big IF and the unlink call but it seems somewhere between file_exists call and unlink, some other process deletes the file ?!

Thanks!

Sorin Trimbitas
  • 1,467
  • 18
  • 35
  • try checking for non-empty `if($file_tmp !='')` – Abhishek Sharma Dec 03 '19 at 08:00
  • @AbhishekSharma If you see the warning issued .. it isn't an issue that file_tmp is empty or not, it is always set – Sorin Trimbitas Dec 03 '19 at 08:03
  • warning says that there is not file or directory that means the `$file_tmp` not set – Abhishek Sharma Dec 03 '19 at 08:06
  • 1
    long shot... _Note: Because PHP's integer type is signed and many platforms use 32bit integers, some filesystem functions may return unexpected results for files which are larger than 2GB._ [manual](https://www.php.net/manual/en/function.file-exists.php) – jibsteroos Dec 03 '19 at 08:35

1 Answers1

1

You can disable error reporting for a while and no need to force supress warnings.

Note: When you try to delete a directory, you must delete all files recursively inside, first.

if ($delete === TRUE)
{
    $file_tmp = $file->getRealPath();
    clearstatcache(TRUE, $file_tmp);
    if (file_exists($file_tmp))
    {
        // store current error reporting level
        $level = error_reporting();

        // turn completely off
        error_reporting(0);

        // unlink and store state
        $state = unlink($file_tmp);

        // restore error reporting level
        error_reporting($level);

        // return unlink state
        return $state;
    }
    return FALSE;
}
Markus Zeller
  • 8,516
  • 2
  • 29
  • 35