Explanation of the Wonderful Use of rename of Function in PHP

  • 2021-11-29 23:13:33
  • OfStack

As we all know, rename() Function can rename a file or directory. In fact, it can do many things.

Those familiar with unix should know the shell command mv, which is equivalent to the move of win32, and can be renamed at the same time. I found that the rename () function of php is equivalent to mv, which not only has simple renaming function, but also can change the path of files and even the whole directory.

For example:

$oldpath--Original path of file or directory

$newpath--New defined path

Then rename ($oldpath, $newpath) can complete the file/directory movement

After my tests, both win32 and php4 versions of unix support this feature.

In addition, it seems that the win 32 version of php 4 eliminates the unlink () function. Then you can also skillfully use the rename () function to complete the deletion operation, for example:

$path--File or directory path

$tmp--tmp Directory (/tmp)

Use rename ($path, $tmp) to move the files to the tmp directory.

There is a method on the Internet is copy+unlink to move files, but it will consume a lot of time when encountering large files, which is not very friendly to performance and can be used rename() To move files, very fast

On rename () Function


bool rename ( string $oldname , string $newname [, resource $context ] )
 Try to put  oldname  Rename to  newname If the operation is successful, return True Failure returns False . 

Note:

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

2. For empty folders, rename () can be moved between drive letters. But the parent directory of the destination folder must exist.

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

Actual column code:


rename("/file1/www.txt", "/file2/my_file.txt");

Summarize


Related articles: