Oihana PHP

copyFile.php

Table of Contents

Functions

copyFile()  : bool
Copies a single file to a destination path.

Functions

copyFile()

Copies a single file to a destination path.

copyFile(string $source, string $destination[, bool $overwrite = true ][, bool $createDirectory = true ]) : bool

Unlike copyFilteredFiles() (which mirrors a whole directory tree), this helper copies one file with explicit, typed error handling:

  • the source is validated with assertFile() (must exist and be readable);
  • if $destination is an existing directory, the file is copied inside it, keeping the source basename (the cp source dir/ convention);
  • copying a file onto itself is refused (it would truncate the source);
  • when $overwrite is false, an existing destination raises a FileException;
  • the destination's parent directory is created on demand when $createDirectory is true.
Parameters
$source : string

Path to the source file to copy.

$destination : string

Destination file path, or an existing directory to copy into.

$overwrite : bool = true

Whether to overwrite an existing destination file (default: true).

$createDirectory : bool = true

Whether to create the destination directory if missing (default: true).

Tags
throws
FileException

If the source is invalid, source and destination are the same file, the destination exists and $overwrite is false, or the copy fails.

DirectoryException

If the destination directory is missing and $createDirectory is false, or cannot be created.

author

Marc Alcaraz (ekameleon)

since
1.2.0
example
use function oihana\files\copyFile;

copyFile( '/data/report.pdf' , '/backup/report.pdf' ) ;          // explicit target
copyFile( '/data/report.pdf' , '/backup' ) ;                     // into a directory
copyFile( '/data/report.pdf' , '/backup/report.pdf' , false ) ;  // throws if it already exists
Return values
bool

Returns true on success.

On this page

Search results