[英]PHP - Rename all files in folder to 1.ext, 2.ext, 3.ext
... and of course, with .ext, I mean, preserve the original extension! ...当然,使用.ext,我的意思是保留原始扩展名!
Now this question has been asked before, but weirdly, the answer doesn't even remotely work. 现在已经有人问过这个问题,但是很奇怪,答案甚至无法远程解决。 For me, that is. 对我而言。
Now, I started with this: 现在,我开始:
$directory = $_SERVER['DOCUMENT_ROOT'].$fileFolder.'/';
$i = 1;
$handler = opendir($directory);
while ($file = readdir($handler)) {
if ($file != "." && $file != "..") {
$newName = $i . '.jpg';
rename($file, $newName);
$i++;
}
}
closedir($handler);
Seems pretty straightforward to me, yet it doesn't rename any files... Does anyone have a clue what is going wrong? 对我来说似乎很简单,但它没有重命名任何文件...是否有人知道出了什么问题? Or just a working snippet... :D 或者只是一个工作片段...:D
You need the full relative/absolute name when you are renaming, not a filename relative to the directory you're currently walking over. 重命名时需要完整的相对/绝对名称,而不是相对于您当前正在浏览的目录的文件名。 But readdir()
returns only the filename relative to the directory you're walking over. 但是readdir()
仅返回相对于您要遍历的目录的文件名。
$directory = $_SERVER['DOCUMENT_ROOT'].$fileFolder.'/';
$i = 1;
$handler = opendir($directory);
while ($file = readdir($handler)) {
if ($file != "." && $file != "..") {
$newName = $i . '.jpg';
rename($directory.$file, $directory.$newName); // here; prepended a $directory
$i++;
}
}
closedir($handler);
readdir()
returns ONLY the filename of the directory you're scanning. readdir()
仅返回您正在扫描的目录的文件名。 Since you opened up a subdir of whatever directory you're running the script, in you need to include that subdir in the rename call, eg: 由于打开了正在运行脚本的任何目录的子目录,因此需要在重命名调用中包含该子目录,例如:
rename($directory . $file, $directory . $newName);
<?
$dir = opendir('test');
$i = 1;
// loop through all the files in the directory
while (false !== ($file = readdir($dir)))
{
// if the extension is '.jpg'
if (strtolower(pathinfo($file, PATHINFO_EXTENSION)) == 'jpg')
{
// do the rename based on the current iteration
$newName = 'test/'. $i . '.jpg';
$new = 'test/'.$file;
rename($new, $newName);
// increase for the next loop
$i++;
}
}
// close the directory handle
closedir($dir);
?>
www.codeprojectdownload.com
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.