Home > Article > Backend Development > How to copy a file and rename it in php
In PHP, you can use the сoру() function to modify the file name after copying the file. This function can copy (copy) a file to the specified directory, the syntax is "copy($file, $newfile) "; Returns TRUE if the execution is successful, and FALSE if the execution fails.
The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer
In PHP, you can use the сoру() function To modify the file name after copying the file.
Example:
There is a folder with only one text file "test.txt" in it. Now I want to copy the file and rename it to "newtest.txt"
Implementation code:
<?php header("Content-type:text/html;charset=utf-8"); $file = 'test.txt'; $newfile = 'newtest.txt'; if(copy($file, $newfile)){ echo '文件复制成功!'; }else{ echo '文件复制失败!'; } ?>
Output result:
Open the folder and look at the files inside , and found that there are two text files:
Let’s take a brief look at the сoру() function:
сoру() function can copy a file ( copy) to the specified directory, returns TRUE if the execution is successful, and returns FALSE if it fails. The syntax format of the function is as follows:
copy(string $source, string $dest[, resource $context])
The parameter description is as follows:
$source: source file path;
$dest : Target path, if the file exists, it will be overwritten. If $dest is a URL, if the encapsulation protocol does not support overwriting existing files, the copy will fail;
$ context: Optional parameter, indicating a valid context resource created using stream_context_create().
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to copy a file and rename it in php. For more information, please follow other related articles on the PHP Chinese website!