PHP Move and Copy File From One Folder to Another
Php 28-Sep-2021

PHP Move and Copy File From One Folder to Another

PHP move and copy file from one folder to another folder. In this tutorial, you will learn How to move a file into a different folder on the server using PHP and as well as How to copy a file into a different folder on the server using PHP?

Move and Copy File From One Folder to Another in PHP

  • PHP Move File From One Folder to Another
  • PHP Copy File From One Folder to Another

PHP Move File From One Folder to Another

If you need to move file from one folder to another using php code then you can use “rename()” function of php. php provide rename function to move your file from one place to another.

First of all, you need to see syntax of rename() function.

Syntax:

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

See the explanation of rename() function parameters are followings:

$source: you need to give file path that you want to rename.

$destination: you need to give file path for destination source.

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

Example:

<?php
   
/* Store the path of source file */
$filePath = 'images/test.jpeg';
   
/* Store the path of destination file */
$destinationFilePath = 'copyImages/test.jpeg';
   
/* Move File from images to copyImages folder */
if( !rename($filePath, $destinationFilePath) ) {  
    echo "File can't be moved!";  
}  
else {  
    echo "File has been moved!";  

   
?>

PHP Copy File From One Folder to Another

If you need to copy file from one folder to another using php code then you can use “copy()” function of php. php provide copy function to move your file from one place to another.

First of all, you need to see syntax of copy() function.

Syntax:

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

See the explanation of copy() function parameters are followings:

$source: you need to give file path that you want to copy.

$destination: you need to give file path for destination source.

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

Example:

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

   
?>