The copy Function

The copy function creates a copy of a file from the source to the specified destination. The first parameter of the function is the path to the source file, the second is the path where the file should be copied to. The function returns true on successful copying and false on error.

Syntax

phpcopy(source, dest);

Example

Let's copy a file from source.txt to destination.txt:

php<?php
  $res = copy('source.txt', 'destination.txt');
  var_dump($res);
?>

Code execution result (if the file was copied successfully):

phptrue

Example

Let's try to copy a non-existent file:

php<?php
  $res = copy('nonexistent.txt', 'destination.txt');
  var_dump($res);
?>

Code execution result:

phpfalse

Example

Copying with a check for the existence of the source file:

php<?php
  if (file_exists('source.txt')) {
    $res = copy('source.txt', 'destination.txt');
    echo $res ? 'File copied' : 'Copy failed';
  } else {
    echo 'Source file not found';
  }
?>

See Also

  • the rename function,
    which renames or moves a file
  • the unlink function,
    which deletes a file
  • the file_exists function,
    which checks for the existence of a file