Home > Article > Backend Development > How to change the name of a file in php
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.
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"
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 = 'test.txt'; if(file_exists($file)){ if(rename($file,'newtest.txt')){ echo $file.' 重命名成功!'; }else{ echo $file.' 重命名失败!'; } }else{ echo $file.' 不存在!'; } ?>
Output results:
Open the folder and look at the files:
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!