Open In App

How to copy a file from one directory to another using PHP ?

Last Updated : 25 Sep, 2019
Comments
Improve
Suggest changes
Like Article
Like
Report
The copy() function in PHP is used to copy a file from source to target or destination directory. It makes a copy of the source file to the destination file and if the destination file already exists, it gets overwritten. The copy() function returns true on success and false on failure. Syntax:
bool copy( string $source, string $destination, resource $context )
Parameters: This function uses three parameters source, destination and context which are listed below:
  • $source: It specifies the path of the source file.
  • $destination: It specifies the path of the destination file or folder.
  • $context: It specifies the context resource created with stream_context_create() function. It is optional parameter.
Return: It returns a boolean value, either true (on success) or false (on failure). Examples:
Input : $source = 'Source_file_location'
        $destination = 'Destination_file_location'
        copy( $source, $destination )

Output: true
PHP
<?php 

// Copy the file from /user/desktop/geek.txt 
// to user/Downloads/geeksforgeeks.txt'
// directory

// Store the path of source file
$source = '/user/Desktop/geek.txt'; 

// Store the path of destination file
$destination = 'user/Downloads/geeksforgeeks.txt'; 

// Copy the file from /user/desktop/geek.txt 
// to user/Downloads/geeksforgeeks.txt'
// directory
if( !copy($source, $destination) ) { 
    echo "File can't be copied! \n"; 
} 
else { 
    echo "File has been copied! \n"; 
} 

?> 
Output:
File has been copied!
Reference: https://www.php.net/manual/en/function.copy.php

Next Article

Similar Reads