Recently, I encountered a strange problem when I was working on the project. The rename function of php seems to delete the file named by a number. Specifically, if there are 10 files in a folder
Recently, I encountered a strange problem when working on the project. The rename function of php seems to delete the file named by a number, as shown in the following code:
If a folder contains 10 files, 1.jpg-10.jpg, And if you run this function,Delete Files other than 1.jpg and 10.jpg.And tested again. It seems that some files will be randomly deleted according to the number of files. The function is as follows:
function getFile($dir){ $dirObj = new \DirectoryIterator($dir); $file = []; $i = 1; foreach ($dirObj as $v) { if ($v->isDot() || $v->isDir()) continue; if ($v->isFile()) { $new = $i . '.' . $v->getExtension(); rename($dir . '/' . $v->getFilename(), $dir . '/' . $new); $file[] = $new; $i++; } } return $file;}
Environment: win7, apache 2.4.9, php 5.5.12
If this is not the reason for rename, it should not be the reason for the DirectoryIterator class. This is before running the function.
This is after running
Reply content:
Recently, I encountered a strange problem when working on the project. The rename function of php seems to delete the file named by a number, as shown in the following code:
If a folder contains 10 files, 1.jpg-10.jpg, And if you run this function,Delete Files other than 1.jpg and 10.jpg.And tested again. It seems that some files will be randomly deleted according to the number of files. The function is as follows:
function getFile($dir){ $dirObj = new \DirectoryIterator($dir); $file = []; $i = 1; foreach ($dirObj as $v) { if ($v->isDot() || $v->isDir()) continue; if ($v->isFile()) { $new = $i . '.' . $v->getExtension(); rename($dir . '/' . $v->getFilename(), $dir . '/' . $new); $file[] = $new; $i++; } } return $file;}
Environment: win7, apache 2.4.9, php 5.5.12
If this is not the reason for rename, it should not be the reason for the DirectoryIterator class. This is before running the function.
This is after running
You only need to trace the two parameter values you passed to rename to know the result.
This is because the sorting of objects is
1. jpg
10. jgp
2. jpg
3. jpg
...
9. jpg
Then, when rename is set
1. jpg-> 1.jpg
10. jpg-> 2.jpg
2. jpg-> 3.jpg
3. jpg-> 4.jpg
...
9. jpg-> 10.jpg
So there are only two files left.