- PHP Copy File
- Introduction to the PHP copy() file function
- PHP copy file examples
- 1) A simple PHP copy file example
- 2) Check if the destination file exists before copying
- 3) PHP copy file helper function
- Summary
- copy
- Parameters
- Return Values
- Examples
- See Also
- User Contributed Notes 24 notes
- PHP copy() Function
- Syntax
- Parameter Values
- Technical Details
- COLOR PICKER
- Report Error
- Thank You For Helping Us!
PHP Copy File
Summary: in this tutorial, you will learn how to copy a file by using the PHP copy() file function from one location to another.
Introduction to the PHP copy() file function
To copy a file from one location to another, you use the copy() function:
copy ( string $source , string $dest , resource $context = ? ) : bool
Code language: PHP (php)
The copy() file function has three parameters:
- $source is the full path to the file that you want to copy.
- $dest is the full path to the file to which the file will copy.
- $context is a valid context resource.
The copy() function returns true if the file is copied successfully or false in case there was an error during copying the file.
Note that if the $dest file exists, the copy() function will overwrite it.
PHP copy file examples
Let’s take some examples of using the copy() function.
1) A simple PHP copy file example
The following example uses the copy() function to copy the readme.txt to readme.bak file:
$source = 'readme.txt'; $dest = 'readme.bak'; echo copy($source, $dest) ? "The file $source was copied to $dest successfully!" : "Error copying the file $source";
Code language: HTML, XML (xml)
2) Check if the destination file exists before copying
The following example uses the copy() function to copy the readme.txt file to the readme.bak file. Also, it checks if the readme.bak exists before overwriting the file:
$source = 'readme.txt'; $dest = 'readme.bak'; !file_exists($source) && die("The file $source does not exist"); file_exists($dest) && die("The file $dest already exists"); echo copy($source, $dest) ? "The file $source was copied to $dest successfully!" : "Error copying the file $source";
Code language: HTML, XML (xml)
3) PHP copy file helper function
The following copy_file() helper function copies a file. It returns false if the source file does not exist or the destination file exists and the overwritten argument is true :
function copy_file($source, $dest, $overwritten = true): bool < if (!file_exists($source)) < return false; > if (!$overwritten && file_exists($dest)) < return false; > return copy($source, $dest); >
Code language: HTML, XML (xml)
Summary
- Use the PHP copy() file function to copy a file from a location to another.
- The copy() function overwrites the destination file if it exists.
copy
If you wish to move a file, use the rename() function.
Parameters
The destination path. If to is a URL, the copy operation may fail if the wrapper does not support overwriting of existing files.
If the destination file already exists, it will be overwritten.
A valid context resource created with stream_context_create() .
Return Values
Returns true on success or false on failure.
Examples
Example #1 copy() example
$file = ‘example.txt’ ;
$newfile = ‘example.txt.bak’ ;
?php
if (! copy ( $file , $newfile )) echo «failed to copy $file . \n» ;
>
?>
See Also
- move_uploaded_file() — Moves an uploaded file to a new location
- rename() — Renames a file or directory
- The section of the manual about handling file uploads
User Contributed Notes 24 notes
Having spent hours tacking down a copy() error: Permission denied , (and duly worrying about chmod on winXP) , its worth pointing out that the ‘destination’ needs to contain the actual file name ! — NOT just the path to the folder you wish to copy into.
DOH !
hope this saves somebody hours of fruitless debugging
It take me a long time to find out what the problem is when i’ve got an error on copy(). It DOESN’T create any directories. It only copies to existing path. So create directories before. Hope i’ll help,
On Windows, php-7.4.19-Win32-vc15-x64 — copy() corrupted a 6GB zip file. Our only recourse was to write:
function file_win_copy( $src, $dst ) shell_exec( ‘COPY «‘.$src.'» «‘.$dst.'»‘);
return file_exists($dest);
>
Don’t forget; you can use copy on remote files, rather than doing messy fopen stuff. e.g.
if(!@ copy ( ‘http://someserver.com/somefile.zip’ , ‘./somefile.zip’ ))
$errors = error_get_last ();
echo «COPY ERROR: » . $errors [ ‘type’ ];
echo «
\n» . $errors [ ‘message’ ];
> else echo «File copied from remote!» ;
>
?>
Here is a simple script that I use for removing and copying non-empty directories. Very useful when you are not sure what is the type of a file.
I am using these for managing folders and zip archives for my website plugins.
// removes files and non-empty directories
function rrmdir ( $dir ) if ( is_dir ( $dir )) $files = scandir ( $dir );
foreach ( $files as $file )
if ( $file != «.» && $file != «..» ) rrmdir ( » $dir / $file » );
rmdir ( $dir );
>
else if ( file_exists ( $dir )) unlink ( $dir );
>
// copies files and non-empty directories
function rcopy ( $src , $dst ) if ( file_exists ( $dst )) rrmdir ( $dst );
if ( is_dir ( $src )) mkdir ( $dst );
$files = scandir ( $src );
foreach ( $files as $file )
if ( $file != «.» && $file != «..» ) rcopy ( » $src / $file » , » $dst / $file » );
>
else if ( file_exists ( $src )) copy ( $src , $dst );
>
?>
Cheers!
A nice simple trick if you need to make sure the folder exists first:
$srcfile = ‘C:\File\Whatever\Path\Joe.txt’ ;
$dstfile = ‘G:\Shared\Reports\Joe.txt’ ;
mkdir ( dirname ( $dstfile ), 0777 , true );
copy ( $srcfile , $dstfile );
Below a code snippet for downloading a file from a web server to a local file.
It demonstrates useful customizations of the request (such as setting a User-Agent and Referrer, often required by web sites), and how to download only files if the copy on the web site is newer than the local copy.
It further demonstrates the processing of response headers (if set by server) to determine the timestamp and file name. The file type is checked because some servers return a 200 OK return code with a textual «not found» page, instead of a proper 404 return code.
// $fURI: URL to a file located on a web server
// $target_file: Path to a local file
if ( file_exists ( $target_file ) ) $ifmodhdr = ‘If-Modified-Since: ‘ . date ( «r» , filemtime ( $target_file ) ). «\r\n» ;
>
else $ifmodhdr = » ;
>
// set request header for GET with referrer for modified files, that follows redirects
$arrRequestHeaders = array(
‘http’ =>array(
‘method’ => ‘GET’ ,
‘protocol_version’ => 1.1 ,
‘follow_location’ => 1 ,
‘header’ => «User-Agent: Anamera-Feed/1.0\r\n» .
«Referer: $source \r\n» .
$ifmodhdr
)
);
$rc = copy ( $fURI , $target_file , stream_context_create ( $arrRequestHeaders ) );
// HTTP request completed, preserve system error, if any
if( $rc ) if ( fclose ( $rc ) ) unset( $err );
>
else $err = error_get_last ();
>
>
else $err = error_get_last ();
>
// Parse HTTP Response Headers for HTTP Status, as well filename, type, date information
// Need to start from rear, to get last set of headers after possible sets of redirection headers
if ( $http_response_header ) for ( $i = sizeof ( $http_response_header ) — 1 ; $i >= 0 ; $i — ) if ( preg_match ( ‘@^http/\S+ (\S) (.+)$@i’ , $http_response_header [ $i ], $http_status ) > 0 ) // HTTP Status header means we have reached beginning of response headers for last request
break;
>
elseif ( preg_match ( ‘@^(\S+):\s*(.+)\s*$@’ , $http_response_header [ $i ], $arrHeader ) > 0 ) switch ( $arrHeader [ 1 ] ) case ‘Last-Modified’ :
if ( !isset( $http_content_modtime ) ) $http_content_modtime = strtotime ( $arrHeader [ 2 ] );
>
break;
case ‘Content-Type’ :
if ( !isset( $http_content_image_type ) ) if ( preg_match ( ‘@^image/(\w+)@ims’ , $arrHeader [ 2 ], $arrTokens ) > 0 ) if ( in_array ( strtolower ( $arrTokens [ 1 ]), $arrValidTypes )) $http_content_image_type = $arrTokens [ 1 ];
break;
>
>
throw new Exception ( «Error accessing file $fURI ; invalid content type: $arrHeader [ 2 ] » , 2 );
>
break;
case ‘Content-Disposition’ :
if ( !isset( $http_content_filename ) && preg_match ( ‘@filename\\s*=\\s*(?|»([^»]+)»|([\\S]+));?@ims’ , $arrHeader [ 2 ], $arrTokens ) > 0 ) $http_content_filename = basename ( $arrTokens [ 1 ]);
>
break;
>
>
>
>
if ( $http_status ) // Make sure we have good HTTP Status
switch ( $http_status [ 1 ] ) case ‘200’ :
// SUCCESS: HTTP Status is «200 OK»
break;
case ‘304’ :
throw new Exception ( «Remote file not newer: $fURI » , $http_status [ 1 ] );
break;
case ‘404’ :
throw new Exception ( «Remote file not found: $fURI » , $http_status [ 1 ] );
break;
default:
throw new Exception ( «HTTP Error, $http_status [ 2 ] , accessing $fURI » , $http_status [ 1 ] );
break;
>
>
elseif ( $err ) // Protocol / Communication error
throw new Exception ( $err [ ‘message’ ] /*.»; Remote file: $fURI»*/ , $err [ ‘type’ ] );
>
else // No HTTP status and no error
throw new customException ( «Unknown HTTP response accessing $fURI : $http_response_header [ 0 ] » , — 1 );
>
?>
Notes:
1. Currently copy() does NOT appropriately handle the 304 response code. Instead of NOT performing a copy (possibly setting the RC), it will overwrite the target file with an zero length file.
2. There may be a problem accessing a list of remote files when HTTP 1.1 protocol is used. If you experience time-out errors, try the default 1.0 protocol version.
PHP copy() Function
Note: If the to_file file already exists, it will be overwritten.
Syntax
Parameter Values
Parameter | Description |
---|---|
from_file | Required. Specifies the path to the file to copy from |
to_file | Required. Specifies the path to the file to copy to |
context | Optional. Specifies a context resource created with stream_context_create() |
Technical Details
Return Value: | TRUE on success, FALSE on failure |
---|---|
PHP Version: | 4.0+ |
PHP Changelog: | PHP 5.3 — Added context parameter |
❮ PHP Filesystem Reference
COLOR PICKER
Report Error
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
Thank You For Helping Us!
Your message has been sent to W3Schools.
Top Tutorials
Top References
Top Examples
Get Certified
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.