Home  >  Article  >  Backend Development  >  How to change the name of a file in php

How to change the name of a file in php

青灯夜游
青灯夜游Original
2021-09-15 11:28:507208browse

In PHP, you can use the rename() function to modify the name of a file. This function can rename a file or directory. The syntax is "rename (file name to be modified, new file name)"; if Returns TRUE if the modification is successful, and FALSE if the modification fails.

How to change the name of a file in php

The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer

In PHP, you can use the rename() function to change the name of the file.

Example: There is a text file named "test.txt"

How to change the name of a file in php

Now I want to modify it to "newtest.txt" , we can use the following code:

<?php
header("Content-type:text/html;charset=utf-8");
$file = &#39;test.txt&#39;;
if(file_exists($file)){
    if(rename($file,&#39;newtest.txt&#39;)){
        echo $file.&#39; 重命名成功!&#39;;
    }else{
        echo $file.&#39; 重命名失败!&#39;;
    }
}else{
    echo $file.&#39; 不存在!&#39;;
}
?>

Output results:

How to change the name of a file in php

Open the folder and look at the files:

How to change the name of a file in php

OK modification successful! Let’s take a brief look at the rename() function:

The rename() function can rename a file or directory. It returns TRUE when successful and FALSE when failed. The syntax format of this function is as follows:

rename(string $oldname, string $newname[, resource $context])

Among them, $oldname is the file name to be modified; $newname is the new file name; $context is an optional parameter, used to specify the environment of the file handle. $context is a set of options that can modify the behavior of the stream.

There are the following points to note when using the rename() function:

  • For non-empty folders, they can only be moved under the same drive letter;

  • For empty folders, rename() can move between different drive letters. But the parent directory of the target folder must exist;

  • For files, rename() can also move between different drive letters.

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of How to change the name of a file 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