delete_directory()
public function delete_directory(string $directory_path): bool
Description
Recursively deletes a directory and all its contents (files and subdirectories). Includes security validation to prevent deletion of restricted paths.
Warning: This operation is irreversible. Use with extreme caution.
Parameters
| Parameter | Type | Description |
|---|---|---|
| $directory_path | string | Absolute or relative path to the directory to delete. |
Return Value
| Type | Description |
|---|---|
| bool | true if the directory was successfully deleted. |
Example Usage
PHP
// Delete a temporary directory
$success = $this->file->delete_directory('uploads/temp/');
if ($success) {
set_flashdata('Directory deleted successfully.');
}
// Delete with error handling
try {
$this->file->delete_directory('cache/');
} catch (Exception $e) {
set_flashdata('Error: ' . $e->getMessage());
}
// Clean up user‑generated content
public function purge_user_data(int $user_id) {
$dir = 'uploads/users/' . $user_id . '/';
if (is_dir($dir)) {
$this->file->delete_directory($dir);
}
}Notes
- Throws
Exceptionif the path is restricted (validated byis_path_valid()). - Throws
Exceptionif the path is not a directory. - Throws
Exceptionif the directory cannot be deleted (e.g., permissions). - Uses recursion to delete nested subdirectories.
- Security: Only allows deletion within permitted application paths (e.g.,
uploads/,cache/).