AL-zami
AL-zami

Reputation: 9066

rename images and move the renamed images in newly created directory

Here i want to create a new directory called c:/xampp/htdocs/haha/tour/ and in the directory i want to move my renamed images .Here ,i managed to create the new directory but can't move and rename my images.How can i solve this problem??

$dir='c:/xampp/htdocs/practice/haha';

$i=1;
if(is_dir($dir)){
echo dirname($dir).'</br>';
     $file=opendir($dir);

     while(($data=readdir($file))!==false){
      if($data!='.' && $data!='..'){

            $info=pathinfo($data,PATHINFO_EXTENSION);

            if(!file_exists($dir.'/tour')){

                    mkdir($dir.'/tour/');

            }

            rename($dir.$data,$dir.'/tour/'.'image '.$i.'.jpg');

            $i++;
         }
      }
     }

Upvotes: 1

Views: 533

Answers (2)

Rizier123
Rizier123

Reputation: 59681

This should work for you:

Here I just get all images from your directory with glob(). I create the directory if it doesn't exist already with mkdir() and then move all images with rename().

<?php

    $dir = "c:/xampp/htdocs/practice/haha";
    $files = glob($dir . "/*.{jpg,png,gif,jepg}", GLOB_BRACE);


    //Create directory
    if (!file_exists($dir . "/tour")) {
        mkdir($dir . "/tour");         
    } 

    //Move all images
    foreach($files as $key => $file) {
        rename($dir . "/" .$data, $dir . "/tour/image" . ($key+1) . ".jpg");
    }

?>

Upvotes: 1

Marc B
Marc B

Reputation: 360632

You're missing some /:

rename($dir.$data,$dir.'/tour/'.'image '.$i.'.jpg');
           ^---

$data doesn't contain ANY /, so what you're building is

rename('c:/xampp/htdocs/practice/haha' . 'foo', etc...)

which becomes

rename('c:/xampp/htdocs/practice/hahafoo', etc...)
                                 ^^^^^^^---doesn't exist

Try

   rename($dir .'/' . $data,$dir.'/tour/'.'image '.$i.'.jpg');
              ^^^^^^^^

instead.

Upvotes: 1

Related Questions