简体   繁体   中英

Why is PHP rename($file) still deleting files?

So I'm using the php rename function to systematically rename all the files in a specific folder.

According to the output buffer, it works fine. When I look in the folder, it is missing files 11-99. I replaced the rename function with my own function below, however I am getting the exact same results.

Code:

function rename_files($directory){
  $path = 'C:\xampp\htdocs\email' . '\\' . $directory . '\\';

  $x = 00001;

 foreach (glob($path."*") as $filename) {
     $newFile = $path . 'list' . $x . '.txt';
     $content = file_get_contents($filename); //this function returns the content of a file.
     echo "$newFile and old $filename<br>";
     unlink($filename);

     $file = fopen($newFile, "w");
     fwrite($file,$content);
     fclose($file);
     ++$x;
  }
}

Output: PHP输出缓冲区

Reality:

在文件夹中创建的实际文件

Your main problem is, that your source and destination directory is the same and the names of the old files and new files are overlapping.

Looking at the first two lines of your output should show you the problem. The newly created file list1.txt is deleted in the second loop iteration.

A simple, but working solution for your problem should be to create a new directory where you move and rename all files ( rename should work for this) and later delete the now empty source directory and replace it with the temporary one.

Some of your new filenames are the same as old filenames.

You renamed list103 (2).txt to list11.txt . This overwrote the original list11.txt . Later, you renamed list11.txt to list25.txt .

As a result, the original list11.txt is lost.

This happens over and over: list1 (2).txt -> list1.txt -> list2.txt

You need to check whether $newFile already exists, and use a different name that doesn't exist. Or perhaps use different naming conventions for the old and new files, so that they can't conflict with each other.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM