Back to File class

Method delete

public static bool
delete
(mixed $file)
Delete a file or array of files
Parameters
  • mixed $file The file name or an array of file names
Returns
  • bool True on success
Since
  • 1.7.0
Class: File
Project: Joomla

Method delete - Source code

/**
 * Delete a file or array of files
 *
 * @param   mixed  $file  The file name or an array of file names
 *
 * @return  boolean  True on success
 *
 * @since   1.7.0
 */
public static function delete($file)
{
    $FTPOptions = ClientHelper::getCredentials('ftp');
    if (\is_array($file)) {
        $files = $file;
    } else {
        $files[] = $file;
    }
    // Do NOT use ftp if it is not enabled
    if ($FTPOptions['enabled'] == 1) {
        // Connect the FTP client
        $ftp = FtpClient::getInstance($FTPOptions['host'], $FTPOptions['port'], array(), $FTPOptions['user'], $FTPOptions['pass']);
    }
    foreach ($files as $file) {
        $file = Path::clean($file);
        if (!is_file($file)) {
            continue;
        }
        /**
         * Try making the file writable first. If it's read-only, it can't be deleted
         * on Windows, even if the parent folder is writable
         */
        @chmod($file, 0777);
        /**
         * Invalidate the OPCache for the file before actually deleting it
         * @see https://github.com/joomla/joomla-cms/pull/32915#issuecomment-812865635
         * @see https://www.php.net/manual/en/function.opcache-invalidate.php#116372
         */
        self::invalidateFileCache($file);
        /**
         * In case of restricted permissions we delete it one way or the other
         * as long as the owner is either the webserver or the ftp
         */
        if (@unlink($file)) {
            // Do nothing
        } elseif ($FTPOptions['enabled'] == 1) {
            $file = Path::clean(str_replace(JPATH_ROOT, $FTPOptions['root'], $file), '/');
            if (!$ftp->delete($file)) {
                // FTP connector throws an error
                return false;
            }
        } else {
            $filename = basename($file);
            Log::add(Text::sprintf('JLIB_FILESYSTEM_DELETE_FAILED', $filename), Log::WARNING, 'jerror');
            return false;
        }
    }
    return true;
}