-3

I want to make a php script that when the images folder has 30 images the next one uploaded becomes 1.JPEG and the rest go up one but the image which was 30.JPEG gets deleted because there is a 30 image limit. Would this even be possible to do? This is what I have tried so far but it gives a unexpected ";" error

<?php
 if(isset($_FILES['image'])){
   $errors= array();
   $file_name = $_FILES['image']['name'];
   $file_size = $_FILES['image']['size'];
   $file_tmp = $_FILES['image']['tmp_name'];
   $file_type = $_FILES['image']['type'];
   $file_ext=strtolower(end(explode('.',$_FILES['image']['name'])));

   $expensions= array("jpeg","jpg","png");

   if(in_array($file_ext,$expensions)=== false){
     $errors[]="extension not allowed, please choose a JPEG or PNG file.";
   }

   if($file_size > 2097152) {
      $errors[]='File size must be excately 2 MB';
   }
  for ($file_tmp = 29; $i > 0; $i--)
 for ($i = 29; $i > 0; $i--)
 {
 if (file_exists($file_tmp.".jpg");
     rename($file_tmp.".jpg",($file_tmp+1).".jpg");
 }      
  if(empty($errors)==true) {
     move_uploaded_file($file_tmp,"images/".$file_name);
     echo "Success";
  }else{
     print_r($errors);
      }
   }
?>
Ben
  • 45
  • 9
  • 1
    please show us what you have tried so far and where you are struggling with this problem. – Florian Moser Feb 28 '16 at 20:08
  • Hi Florian I just have a simple php upload script but I was wondering if this is theoretically possible – Ben Feb 28 '16 at 20:10
  • 1
    These may help you some http://stackoverflow.com/questions/12801370/count-how-many-files-in-directory-php - http://stackoverflow.com/questions/14194173/count-number-of-files-in-folder-in-php – Funk Forty Niner Feb 28 '16 at 20:14
  • 3
    It's theoretically possible. – Sven Feb 28 '16 at 20:14
  • 1
    if I understood your question correctly, I would say it is possible. There is the `rename` function to rename a file, and you can check with a for loop through all filenames – Florian Moser Feb 28 '16 at 20:14
  • Thank you I will give it a go :) – Ben Feb 28 '16 at 20:15

1 Answers1

3

I would do it like this:

for ($i = 29; $i > 0; $i--)
{
    if (file_exists($i.".jpg");
         rename($i.".jpg",($i+1).".jpg");
}

Now save your new file as "1.jpg".

I'm sure you could have come up with a similar solution rather quick.

Florian Moser
  • 2,583
  • 1
  • 30
  • 40