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
| Parameter | Type | Description |
| $source_path |
string |
Path to the source file. |
| $destination_path |
string |
Path to the destination. |
Return Value
| Type | Description |
| bool |
Returns true on success. |
Example #1
The code sample below demonstrates the most basic file copy operation.
$source_path = 'modules/documents/original.pdf';
$destination_path = 'modules/documents/copy_of_original.pdf';
// Check if source file exists
if ($this->file->exists($source_path)) {
$result = $this->file->copy($source_path, $destination_path);
if ($result === true) {
echo 'File copied successfully';
}
} else {
echo 'Source file not found';
}
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.
public function update_profile_picture(): void {
$user_id = segment(3, 'int');
// Get user record
$user = $this->db->get_where($user_id, 'users');
if ($user === false) {
redirect('users/not_found');
}
$current_picture = $user->profile_picture; // e.g., 'profile_123.jpg'
$source_path = 'modules/users/pictures/' . $current_picture;
// Check if current profile picture exists before backing it up
if ($this->file->exists($source_path)) {
// Create backup directory if it doesn't exist
$backup_dir = 'modules/users/pictures/backups';
if (!$this->file->exists($backup_dir)) {
$this->file->create_directory($backup_dir, 0755);
}
// Create timestamped backup
$timestamp = date('Y-m-d_His');
$backup_filename = pathinfo($current_picture, PATHINFO_FILENAME) . '_' . $timestamp . '.' . pathinfo($current_picture, PATHINFO_EXTENSION);
$backup_path = $backup_dir . '/' . $backup_filename;
// Copy the file
$result = $this->file->copy($source_path, $backup_path);
if ($result === true) {
// Now safe to process new upload
set_flashdata('Previous picture backed up successfully');
redirect('users/upload_new_picture/' . $user_id);
}
} else {
// No existing picture to backup
redirect('users/upload_new_picture/' . $user_id);
}
}
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.