In PHP development, copying files is a common task. The copy() function allows you to copy a source file to a target file quickly and easily.
The copy() function is simple to use and requires two parameters: the source file path and the destination file path. Here is an example:
<?php
$source_file = "example.txt";
$target_file = "copy_example.txt";
if(copy($source_file, $target_file)) {
echo "File copied successfully!";
} else {
echo "File copy failed!";
}
?>In this example, the source file "example.txt" is copied to the target file "copy_example.txt". If the copy is successful, it will output "File copied successfully!"; otherwise, it will output "File copy failed!".
The copy() function is suitable only for copying files, not directories. If a file with the same name already exists in the destination path, it will be overwritten. If there is no existing file, a new file will be created.
The copy() function also supports copying remote files. You can specify the source file as a URL:
<?php
$source_file = "http://example.com/remotefile.txt";
$target_file = "localfile.txt";
if(copy($source_file, $target_file)) {
echo "Remote file copied successfully!";
} else {
echo "Remote file copy failed!";
}
?>In this example, the remote file "http://example.com/remotefile.txt" is copied to the local file "localfile.txt".
The copy() function returns a boolean value: true if the copy operation is successful, or false if it fails. Developers can handle the result accordingly.
The copy() function in PHP is a useful tool for file copying. It works efficiently for both local and remote files. When using it, pay attention to whether the destination file already exists and handle the copy result appropriately.