delete()

public function delete(string $file_path): bool

Description

Deletes a file from the filesystem. Throws an exception if the file does not exist, cannot be deleted, or is in a restricted path.

Parameters

ParameterTypeDescription
$file_path string The path to the file to be deleted.

Return Value

TypeDescription
bool Returns true if the file is successfully deleted.

Example #1

The code sample below demonstrates the most basic file deletion operation.

Check Before You Act: The delete() method throws an exception if the file doesn't exist or cannot be deleted. It's recommended to always check if a file exists using $this->file->exists($file_path) before attempting deletion. This allows you to handle missing files gracefully with redirects or user-friendly messages, rather than relying on exception handling for expected conditions.

Example #2

The example above shows how to delete a user's uploaded resume file when they request its removal.

Example #3

The example above demonstrates how to delete temporary files after processing is complete.

Example #4

The example above shows how to delete old backup files as part of a maintenance routine.

Database Consistency: When deleting files that are referenced in your database, always update or remove the database record after a successful deletion. Failing to do this will result in broken file references and "file not found" errors when users try to access files that no longer exist on the filesystem.