In this tutorial, we will teach you about PHP’s copy () function and show you how to use PHP copy function.
At the same time, we will also explain the definition, syntax, parameters of copy () and several examples of copy () of PHP. Which will help you a lot in understanding how the copy function works. And how can you use it?
PHP: Copy() Function Example
This copy function is a pre-built function of PHP. Mainly that which is used to copy a file. It copies the given file to the destination file. If the destination file already exists. It is overwritten. The copy () function returns false on fail and true on success.
syntax
The syntax of php copy() funcition is following
copy ( $source file, $destination file )
Note:- This function takes 2 parameters, first source file, and second destination file.
Parameters description
$source file: It specifies the path to the source file.
$destination file: It is used to specify the path to the destination file.
Return Value: It returns false on fail and true on success.
Example 1 :- PHP copy file
To copy a file from one folder to the same folder. We can easily create a copy or duplicate file to original in PHP with PHP’s built-in function called copy().
<?php
// Copying text.txt to newText.txt
echo copy("text.txt", "newText.txt");
?>
Result of the above code is the following:
True
Example 2:- PHP copy file to another directory and rename
To copy a file from one folder to another directory folder.We can easily create a copy or duplicate file to original in PHP with PHP’s built-in function called copy().
<?php
// Copying text.txt to newText.txt
$sourceFile = '/user01/Desktop/myFolder/text.txt';
$destinationFile = 'user01/Desktop/myFolder2/newText.txt';
if (!copy($sourceFile, $destinationFile)) {
echo "File has not been copied! \n";
}
else {
echo "File has been copied!";
}
?>
Result of the above code is the following:
File has been copied!
Example 3:- copy image from one folder to another in PHP
To copy a file from one folder to another or the same folder.We can easily create a copy or duplicate file to original in PHP with PHP’s built-in function called copy().
<?php
$file = '/usr/home/myFolder/image.png';
$newfile = '/usr/home/myFolder/image.png';
if (!copy($file, $newfile)) {
echo "failed to copy $file...\n";
} else {
echo "copied $file into $newfile\n";
}
?>