代码之家  ›  专栏  ›  技术社区  ›  John

在php中随机重命名文件

  •  0
  • John  · 技术社区  · 8 年前

    我有一个包含1000个图像的文件夹,我需要随机将它们从1.jpg重命名为1000.jpg,每次运行脚本时都必须是完全随机的。

    到目前为止,我只需要使用以下代码。

    <?php
    
    if (file_exists('Image00001.jpg'))
    {
    $renamed= rename('Image00001.jpg', '1.jpg');
    
    if ($renamed)
    {
    echo "The file has been renamed successfully";
    }
    else
    {
    echo "The file has not been successfully renamed";
    }
    }
    else
    {
    echo "The original file that you want to rename does not exist";
    }
    
    ?>
    
    1 回复  |  直到 8 年前
        1
  •  2
  •   Harshad Shettigar    8 年前

    看看这个,如果有用的话。我试过了,很管用。创建一个php文件并复制代码,然后在同一目录中创建一个文件夹名 用扩展的图像填充它 jpg先生 然后运行php文件。这是精炼的代码。让我知道这是否适合你。

    <?php
    $dir    = 'files/'; //directory
    $files1 = scandir($dir);
    shuffle($files1); //shuffle file names
    $i           = 1; //initialize counter
    //store existing numbered files in array
    $exist_array = array();
    while (in_array($i . ".jpg", $files1)) {
        array_push($exist_array, $i . ".jpg");
        $i++;
    }
    foreach ($files1 as $ff) {
        if ($ff != '.' && $ff != '..') // check for current or parent directory, else it will replace the directory name
            {
            // check whether the file is already numbered
            if (in_array($ff, $exist_array)) {
                continue;
            }
            //next 3 lines is proof of random rename
            echo $ff . "         --->     ";
            rename($dir . $ff, $dir . $i . ".jpg");
            echo $i . ".jpg<br/>";
            $i++;
        }
    }
    ?> 
    
    推荐文章