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: The copy() function in PHP accepts two parameters which are source and destination.

  1. $source: It specifies the path to the source file.
  2. $dest: It is used to specify the path to the destination file.

Return Value: It returns true on success and false on failure.

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";
}
 
?>

Leave a Reply

Your email address will not be published.