How to copy files from one directory to another with an example

How to copy files from one directory to another with an example

Hello guys, in this article i will let you know how to copy files from one directory to another directory. We generally need to create a feature where we need to copy a file or image from one directory to another directory in a web application. So here i will give you an example to copy file programatically in PHP.

There is a inbuilt method copy to copy files in the php. We can use this copy method simply in our script. Syntax of this method is as under-

bool copy( string $source, string $destination, resource $context )

Here bool is return type, means this method return boolean value like true or files and description of the parameter is as –

$source: In this parameter we will need to give file path that we want to copy.

$destination: In this parameter we will need to give file path for destination source.

$context: this is optional, It specifies the context resource created with stream_context_create() function.

So now let’s do this using a simple example.

Example:

<?php
  
/* Store the path of source file */
$filePath = 'temp/testimage.jpeg';
  
/* Store the path of destination file */
$destinationFilePath = 'images/testimage.jpeg';
  
/* Copy File from temp to images directory */
if( !copy($filePath, $destinationFilePath) ) {  
    echo "File can't be copied!";  
}  
else {  
    echo "File has been copied!";  
} 
  
?>

I hope after the following of above example you will be able to copy files from one directory to another directory in php.