In this tutorial, you will learn How to move a file into a different folder or directory on the server using PHP and 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
Here are ways:
PHP Move File From One Folder to Another
If you need to move file from one folder/directory 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 // define the source and destination paths $source = '/path/to/source/file.txt'; $destination = '/path/to/destination/folder/'; // move the file to the destination folder if (rename($source, $destination . basename($source))) { echo 'File was successfully moved'; } else { echo 'Error moving file'; } ?>
PHP Copy File From One Folder to Another
If you need to copy file from one folder/directory 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:
$source_file = '/path/to/source/file.jpg'; $destination_file = '/path/to/destination/file.jpg'; if (copy($source_file, $destination_file)) { echo "File copied successfully."; } else { echo "Error copying file."; }
Conclusion
In this tutorial, you have learned how to move and copy a file into a different folder or directory on the server using PHP functions.