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
copy(source, dest);
Example
Let's copy a file from source.txt to destination.txt:
<?php
$res = copy('source.txt', 'destination.txt');
var_dump($res);
?>
Code execution result (if the file was copied successfully):
true
Example
Let's try to copy a non-existent file:
<?php
$res = copy('nonexistent.txt', 'destination.txt');
var_dump($res);
?>
Code execution result:
false
Example
Copying with a check for the existence of the source file:
<?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
renamefunction,
which renames or moves a file -
the
unlinkfunction,
which deletes a file -
the
file_existsfunction,
which checks for the existence of a file