Home  >  Article  >  Backend Development  >  How to copy a file and rename it in php

How to copy a file and rename it in php

青灯夜游
青灯夜游Original
2021-09-15 19:04:342910browse

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.

How to copy a file and rename it in php

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"

How to copy a file and rename it in php

Implementation code:

<?php
header("Content-type:text/html;charset=utf-8");
$file    = &#39;test.txt&#39;;
$newfile = &#39;newtest.txt&#39;;
if(copy($file, $newfile)){
    echo &#39;文件复制成功!&#39;;
}else{
    echo &#39;文件复制失败!&#39;;
}
?>

Output result:

How to copy a file and rename it in php

Open the folder and look at the files inside , and found that there are two text files:

How to copy a file and rename it in php

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn