Найти в Дзене

PHP Функции копирования папок "один в один"

Вот функция для копирования всех файлов из папки А в папку Б: function copyAllFiles($sourceDir, $destinationDir) { // Проверяем существование исходной папки if (!is_dir($sourceDir)) { throw new Exception("Исходная папка не существует: " . $sourceDir); } // Создаем целевую папку если не существует if (!is_dir($destinationDir)) { if (!mkdir($destinationDir, 0755, true)) { throw new Exception("Не удалось создать целевую папку: " . $destinationDir); } } // Получаем все файлы из исходной папки $files = array_diff(scandir($sourceDir), ['.', '..']); $copiedCount = 0; $errors = []; foreach ($files as $file) { $sourcePath = $sourceDir . DIRECTORY_SEPARATOR . $file; $destinationPath = $destinationDir . DIRECTORY_SEPARATOR . $file; // Копируем только файлы (не папки) if (is_file($sourcePath)) { if (copy($sourcePath, $destinationPath)) { $copiedCount++; } else { $errors[] = "Не удалось скопировать: " . $file; } } } return [ 'copied' => $copiedCount, 'errors' => $errors, 'total' => count($files) ]
Оглавление

Вот функция для копирования всех файлов из папки А в папку Б:

1. Базовая функция копирования

function copyAllFiles($sourceDir, $destinationDir) {
// Проверяем существование исходной папки
if (!is_dir($sourceDir)) {
throw new Exception("Исходная папка не существует: " . $sourceDir);
}
// Создаем целевую папку если не существует
if (!is_dir($destinationDir)) {
if (!mkdir($destinationDir, 0755, true)) {
throw new Exception("Не удалось создать целевую папку: " . $destinationDir);
}
}
// Получаем все файлы из исходной папки
$files = array_diff(scandir($sourceDir), ['.', '..']);
$copiedCount = 0;
$errors = [];
foreach ($files as $file) {
$sourcePath = $sourceDir . DIRECTORY_SEPARATOR . $file;
$destinationPath = $destinationDir . DIRECTORY_SEPARATOR . $file;
// Копируем только файлы (не папки)
if (is_file($sourcePath)) {
if (copy($sourcePath, $destinationPath)) {
$copiedCount++;
} else {
$errors[] = "Не удалось скопировать: " . $file;
}
}
}
return [
'copied' => $copiedCount,
'errors' => $errors,
'total' => count($files)
];
}

2. Улучшенная версия с рекурсией

function copyAllFilesRecursive($sourceDir, $destinationDir, $overwrite = false) {
if (!is_dir($sourceDir)) {
throw new Exception("Исходная папка не существует: " . $sourceDir);
}
if (!is_dir($destinationDir)) {
mkdir($destinationDir, 0755, true);
}
$iterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($sourceDir, RecursiveDirectoryIterator::SKIP_DOTS),
RecursiveIteratorIterator::SELF_FIRST
);
$copiedCount = 0;
$errors = [];
foreach ($iterator as $item) {
$targetPath = $destinationDir . DIRECTORY_SEPARATOR . $iterator->getSubPathName();
if ($item->isDir()) {
if (!is_dir($targetPath)) {
mkdir($targetPath, 0755, true);
}
} else {
// Проверяем нужно ли перезаписывать существующие файлы
if (!$overwrite && file_exists($targetPath)) {
continue;
}
if (copy($item->getPathname(), $targetPath)) {
$copiedCount++;
} else {
$errors[] = "Не удалось скопировать: " . $item->getFilename();
}
}
}
return [
'copied' => $copiedCount,
'errors' => $errors
];
}

3. Функция с фильтрацией по расширениям

function copyFilesWithFilter($sourceDir, $destinationDir, $allowedExtensions = []) {
if (!is_dir($sourceDir)) {
throw new Exception("Исходная папка не существует: " . $sourceDir);
}
if (!is_dir($destinationDir)) {
mkdir($destinationDir, 0755, true);
}
$files = array_diff(scandir($sourceDir), ['.', '..']);
$copiedCount = 0;
$errors = [];
foreach ($files as $file) {
$sourcePath = $sourceDir . DIRECTORY_SEPARATOR . $file;
if (!is_file($sourcePath)) {
continue;
}
// Фильтрация по расширению
if (!empty($allowedExtensions)) {
$extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));
if (!in_array($extension, $allowedExtensions)) {
continue;
}
}
$destinationPath = $destinationDir . DIRECTORY_SEPARATOR . $file;
if (copy($sourcePath, $destinationPath)) {
$copiedCount++;
} else {
$errors[] = $file;
}
}
return [
'copied' => $copiedCount,
'errors' => $errors
];
}

4. Примеры использования

// Пример 1: Простое копирование
$result = copyAllFiles('/path/to/source', '/path/to/destination');
echo "Скопировано файлов: " . $result['copied'] . " из " . $result['total'];
// Пример 2: Копирование с перезаписью
$result = copyAllFilesRecursive('/path/to/source', '/path/to/destination', true);
// Пример 3: Копирование только изображений
$result = copyFilesWithFilter('/path/to/source', '/path/to/destination', ['jpg', 'png', 'gif']);
echo "Скопировано изображений: " . $result['copied'];
// Пример 4: С обработкой ошибок
try {
$result = copyAllFiles('/path/to/source', '/path/to/destination');
if (!empty($result['errors'])) {
echo "Ошибки при копировании:\n";
foreach ($result['errors'] as $error) {
echo "- " . $error . "\n";
}
}
echo "Успешно скопировано: " . $result['copied'] . " файлов\n";
} catch (Exception $e) {
echo "Ошибка: " . $e->getMessage();
}

5. Функция с прогрессом и логированием

function copyFilesWithProgress($sourceDir, $destinationDir, $callback = null) {
if (!is_dir($sourceDir)) {
throw new Exception("Исходная папка не существует");
}
if (!is_dir($destinationDir)) {
mkdir($destinationDir, 0755, true);
}
$files = array_filter(
array_diff(scandir($sourceDir), ['.', '..']),
function($file) use ($sourceDir) {
return is_file($sourceDir . DIRECTORY_SEPARATOR . $file);
}
);
$total = count($files);
$copied = 0;
$errors = [];
foreach ($files as $file) {
$sourcePath = $sourceDir . DIRECTORY_SEPARATOR . $file;
$destinationPath = $destinationDir . DIRECTORY_SEPARATOR . $file;
if (copy($sourcePath, $destinationPath)) {
$copied++;
if ($callback) {
$callback($file, $copied, $total, 'success');
}
} else {
$errors[] = $file;
if ($callback) {
$callback($file, $copied, $total, 'error');
}
}
}
return [
'copied' => $copied,
'errors' => $errors,
'total' => $total
];
}
// Использование с callback
$result = copyFilesWithProgress('/path/to/source', '/path/to/destination',
function($file, $current, $total, $status) {
echo "Файл: $file | $current/$total | $status\n";
}
);

Выберите подходящую функцию в зависимости от ваших потребностей!