copy()

public function copy(string $source_path, string $destination_path): bool

Description

Copies a file from one location to another. Validates access to the source path before copying.

Parameters

ParameterTypeDescription
$source_path string Path to the source file.
$destination_path string Path to the destination.

Return Value

TypeDescription
bool Returns true on success.

Example #1

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

The "Check Before You Act" Pattern: Always verify the source file exists using $this->file->exists($source_path) before calling copy(). Additionally, ensure the destination directory exists or create it first. This prevents exceptions and allows you to handle missing files gracefully with user-friendly messages or redirects.

Example #2

The example above shows how to create a backup copy of a user's profile picture before processing a new upload.

Copy vs Move: The copy() method duplicates the file, leaving the original in place. If you want to relocate the file (removing it from the source), use move() instead. Copy operations require more disk space and take longer than move operations since they duplicate the file data.