Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm struggling to find any information on looping through all subfolders within a folder and renaming them using PHP. I am renaming them so that I do not reach any limits on numbers of subfolders.

At the moment my user folder structure is as follows :

images/logos/1216/logo.jpg
images/logos/11437/logo.jpg
images/logos/234438/logo.jpg

So I want to loop through all folders within the 'logos' and rename them as follows :

images/users/1/1216/logos/logo.jpg
images/users/11/11437/logos/logo.jpg
images/users/234/234438/logos/logo.jpg

To calculate the new subfolder name, i'm going to take the existing user id (i.e. 11437 and divide by 1000).

The actual issue is how, do I loop through all the subfolders and what is the best way to rename the folder structure.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
349 views
Welcome To Ask or Share your Answers For Others

1 Answer

If I'm correct about the first line of code here you sholud get an array lookin like the second line. Test that first and make a backup of your files.

This should list all userid's or directories and loop through them.
If the copy is success (true) it unlinks the old file, else returns a error message.

This is untested code

//$arr = array_filter(glob('images/logos/*'), 'is_dir');
$arr = array("images/logos/1216","images/logos/11437","images/logos/234438");
//var_dump($arr);

foreach($arr as $dir){
    $UID = str_replace("images/logos/", "", $dir);
    $newpath = "images/users/" . floor($UID/1000) . "/" . $UID . "/logos/logo.jpg";
    $oldpath = $dir . "/logo.jpg";
    if(copy($oldpath, $newpath)){
        unlink($oldpath);
    }else{
        echo "error with file " . $oldpath . "<br>
";
        $error = true;
    }
}

if(!$error) unlink("images/logos");

EDIT; Just noticed I had used Excel too much lately. Changed the & to .
EDIT2; tested the code on my own page now and it seems the glob returns the path. Included code to get the UserID.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...