[英]randomly rename files in php
我有一個包含1000張圖像的文件夾,我需要將它們從1.jpg隨機重命名為1000.jpg,每次運行腳本時它必須完全隨機。 每次運行腳本時,我只需要1.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";
}
?>
如果有幫助,請檢查一下。 我嘗試了一下,它可以工作。 創建一個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++;
}
}
?>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.