views:

33

answers:

2

hello, 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

+1  A: 

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:

if(file_exists($k.".".$ext)) {
    $k .= ".0" ;
}
while(file_exists($k.".".$ext)) {
    $k .= "0" ;
}
$k = $k.".".$ext;
rename($file,$k);

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.

Gus
sorry i am so dump how can i not have seen that! well it was already late ;D thanks!
Joe Hopfgartner
+1  A: 

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:

if(!is_file($k)) {
    rename($file, $k);
}
lawnjam