Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
356 views
in Technique[技术] by (71.8m points)

directory - loop and rename all subfolders in php

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...