Oihana PHP

copyFilteredFiles.php

Table of Contents

Functions

copyFilteredFiles()  : bool
Recursively copies files and directories from a source to a destination with filtering.

Functions

copyFilteredFiles()

Recursively copies files and directories from a source to a destination with filtering.

copyFilteredFiles(string $sourceDir, string $destDir[, array<string|int, string> $excludePatterns = [] ][, callable|null $filterCallback = null ]) : bool

This function iterates through a source directory and copies its contents to a destination directory, preserving the folder structure. It provides two methods for filtering which files and directories get copied:

  1. $excludePatterns: An array of glob/regex patterns. Any file or directory matching a pattern in this array will be skipped. See shouldExcludeFile().
  2. $filterCallback: An optional user-defined function. This callback receives the full path of each item and must return true for the item to be copied.

Destination directories are created as needed.

Parameters
$sourceDir : string

The path to the source directory to copy from.

$destDir : string

The path to the destination directory.

$excludePatterns : array<string|int, string> = []

An array of patterns to exclude from the copy.

$filterCallback : callable|null = null

Optional callback for custom filtering. It receives the file path and should return true to include it.

Tags
throws
DirectoryException

If a directory cannot be created in the destination path.

example

Source directory structure:

/tmp/source/
├── .git/
│   └── config
├── images/
│   └── logo.png  (size: 5KB)
├── index.php     (size: 1KB)
└── error.log
$source = '/tmp/source';
$destination = '/tmp/destination';

// Exclude .git directories and all .log files.
$exclude = ['.git', '*.log'];

// Only include files smaller than 2KB (2048 bytes).
$filter = function(string $filePath)
{
   return is_dir($filePath) || filesize($filePath) < 2048;
};

copyFilteredFiles($source, $destination, $exclude, $filter);

Resulting destination directory:

/tmp/destination/
├── images/
└── index.php

Explanation:

  • .git/ was skipped by the exclude pattern.
  • error.log was skipped by the exclude pattern.
  • images/logo.png was skipped by the filter callback (size > 2KB).
  • index.php was copied as it passed both filters.
author

Marc Alcaraz (ekameleon)

since
1.0.0
Return values
bool

Returns true if at least one file or directory was copied, false otherwise.


        
On this page

Search results