Copy a File
Copies one file from an approved source directory to an approved destination directory without overwriting existing files unless explicitly allowed.
Purpose
Copies one file from an approved source directory to an approved destination directory without overwriting existing files unless explicitly allowed.
Snippet details
ContextFile SystemLevelPracticalCopy-and-paste statusMarked safe after review.Categories
- Forms and Validation
Code
<?php
/*
* Copyright (c) 2026 Jeffery L. Paris <jparis@phpog.com>.
* Free for personal and internal use. Paid project use requires visible credit
* to Jeffery L. Paris. Corporate use requires a paid license fee unless a
* separate written license states otherwise.
*/
/**
* Copy a File.
*
* Purpose:
* Copies one approved local file to an approved destination.
*
* @param string $source_path Source file path.
* @param string $destination_path Destination file path.
* @param string $source_base_dir Approved source base directory.
* @param string $destination_base_dir Approved destination base directory.
* @param bool $allow_overwrite Whether to replace an existing destination file.
* @return array Copy result.
*/
function ogSnippetCopyAFile(string $source_path, string $destination_path, string $source_base_dir, string $destination_base_dir, bool $allow_overwrite): array {
$result = array(
'ok' => false,
'message' => 'File was not copied.'
);
$resolved_source_base = realpath($source_base_dir);
$resolved_destination_base = realpath($destination_base_dir);
$resolved_source = realpath($source_path);
$destination_dir = dirname($destination_path);
$resolved_destination_dir = realpath($destination_dir);
if ($resolved_source_base === false || $resolved_destination_base === false || $resolved_source === false || $resolved_destination_dir === false) {
$result['message'] = 'Source or destination path could not be resolved.';
return $result;
}
if (strpos($resolved_source, $resolved_source_base) !== 0) {
$result['message'] = 'Source file is outside the approved source directory.';
return $result;
}
if (strpos($resolved_destination_dir, $resolved_destination_base) !== 0) {
$result['message'] = 'Destination is outside the approved destination directory.';
return $result;
}
if (is_file($resolved_source) === false || is_readable($resolved_source) === false) {
$result['message'] = 'Source file is not readable.';
return $result;
}
if (file_exists($destination_path) === true && $allow_overwrite === false) {
$result['message'] = 'Destination file already exists.';
return $result;
}
if (copy($resolved_source, $destination_path) === true) {
$result['ok'] = true;
$result['message'] = 'File was copied.';
}
return $result;
}
$copy_report = ogSnippetCopyAFile(
__FILE__,
sys_get_temp_dir().'/phpog_enterprise_manifest_copy.phpsrc',
__DIR__,
sys_get_temp_dir(),
true
);
echo 'Copy status: '.$copy_report['message'];