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

How to change the name of a file in php

青灯夜游
Release: 2023-03-12 15:14:01
Original
7265 people have browsed it

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;;
}
?>
Copy after login

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])
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template