Summary: in this tutorial, you will learn how to copy a file by using the PHP copy()
file function from one location to another.
Introduction to the PHP copy() file function
To copy a file from one location to another, you use the copy()
function:
copy ( string $source , string $dest , resource $context = ? ) : bool
Code language: PHP (php)
The copy()
file function has three parameters:
$source
is the full path to the file that you want to copy.$dest
is the full path to the file to which the file will copy.$context
is a valid context resource.
The copy()
function returns true
if the file is copied successfully or false
in case there was an error during copying the file.
Note that if the $dest
file exists, the copy()
function will overwrite it.
PHP copy file examples
Let’s take some examples of using the copy()
function.
1) A simple PHP copy file example
The following example uses the copy()
function to copy the readme.txt
to readme.bak
file:
<?php
$source = 'readme.txt';
$dest = 'readme.bak';
echo copy($source, $dest)
? "The file $source was copied to $dest successfully!"
: "Error copying the file $source";
Code language: HTML, XML (xml)
2) Check if the destination file exists before copying
The following example uses the copy()
function to copy the readme.txt
file to the readme.bak
file. Also, it checks if the readme.bak
exists before overwriting the file:
<?php
$source = 'readme.txt';
$dest = 'readme.bak';
!file_exists($source) && die("The file $source does not exist");
file_exists($dest) && die("The file $dest already exists");
echo copy($source, $dest)
? "The file $source was copied to $dest successfully!"
: "Error copying the file $source";
Code language: HTML, XML (xml)
3) PHP copy file helper function
The following copy_file()
helper function copies a file. It returns false if the source file does not exist or the destination file exists and the overwritten argument is true
:
<?php
function copy_file($source, $dest, $overwritten = true): bool
{
if (!file_exists($source)) {
return false;
}
if (!$overwritten && file_exists($dest)) {
return false;
}
return copy($source, $dest);
}
Code language: HTML, XML (xml)
Summary
- Use the PHP
copy()
file function to copy a file from a location to another. - The
copy()
function overwrites the destination file if it exists.