php 重命名行为奇怪?
我有这个脚本,我将完全未修改地发布该脚本:
<?
chdir("data");
$files = glob("*");
shuffle($files);
var_dump($files);
$i=0;
$finfo = finfo_open(FILEINFO_MIME_TYPE); // return mime type ala mimetype extension
foreach($files as $file) {
$i++;
$k = $i;
$mime = finfo_file($finfo, $file);
if(strpos($mime,"gif") !== false) {
$ext = "gif";
} else {
$ext = "jpg";
}
if($k < 10) {
$k = "00".$k;
} else if($k < 100) {
$k = "0".$k;
}
$k = $k.".".$ext;
rename($file,$k);
echo $k."\n";
}
文件夹数据中有一些图像文件(jpg 和 gif)。 但是当我运行它时,突然很多图像都消失了! 2/3的图片被删除了... 我不明白怎么办? 我有一个 ext3 文件系统和 PHP 5.3.2
i have this script which i will post absolutely unmodified:
<?
chdir("data");
$files = glob("*");
shuffle($files);
var_dump($files);
$i=0;
$finfo = finfo_open(FILEINFO_MIME_TYPE); // return mime type ala mimetype extension
foreach($files as $file) {
$i++;
$k = $i;
$mime = finfo_file($finfo, $file);
if(strpos($mime,"gif") !== false) {
$ext = "gif";
} else {
$ext = "jpg";
}
if($k < 10) {
$k = "00".$k;
} else if($k < 100) {
$k = "0".$k;
}
$k = $k.".".$ext;
rename($file,$k);
echo $k."\n";
}
the folder data has some image files (jpg and gif) in it.
but when i run it, suddenly a lot of images are just gone!
2/3rd of the images just got deleted...
i don't understand how?
i have an ext3 filesystem and PHP 5.3.2
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我在代码中看不到任何肯定会导致此行为的内容。我能想到的最可能的原因可能是
rename($file,$k);
正在覆盖已经存在的文件。您可以添加以下内容来排除这种情况:我的另一个想法是
chdir("data")
可能出了问题,您可以通过在 $file 之前插入完整路径来检查,然后调用重命名时$k。但我认为这不太可能。I can't see anything in the code that would definately cause this behaviour. The most likely cause I could think of is perhaps
rename($file,$k);
is overwriting files that already exist. You could add the following to rule this out:The other thought I had is that perhaps something is going wrong with the
chdir("data")
which you could check by inserting the full path before $file and $k when calling the rename. I don't think this is very likely though.你运行了两次吗?
第一次运行它时,它会将所有图像重命名为 0001.jpg - 00nn.jpg。第二次它开始覆盖内容,因为源名称和目标名称会重叠,例如它将 0042.jpg 重命名为 0001.jpg,因此现有的 0001.jpg 消失了。
在将 $file 重命名为 $k 之前最好检查 $k 是否存在:
Did you run it twice?
The first time you run it it renames all the images to 0001.jpg - 00nn.jpg. The second time it starts overwriting stuff, because the source names and target names would overlap, e.g. it renames 0042.jpg to 0001.jpg, so the existing 0001.jpg disappears.
Would be good to check if $k exists before renaming $file to $k: