[英]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.