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
400 views
in Technique[技术] by (71.8m points)

php - Recursively chmod/chown/chgrp all files and folder within a directory

I am working on a site which builds other sites. Some if it I use copy() to create the files and directories, other times I'm building XML files in php and using DOMDocument::save to save them. The end result is a root folder with all sorts of messed up permissions. I've beening modding files and folders as I go, which words to some extent, but I'm particularly having trouble when it comes to using copy().

(This is where I'm at so far http://pastebin.com/SBE8vtFX, attn: function modPath($path))

I want to take a different approach and recursively chmod/chown/chgrp all the files and folders within my document root to my specifications at once.

Take for example the document root

/home/mysite/public_html

and within public_html I have

-rwxrwxrwx  1 mysite mysite  348 Aug 31 10:49 index.php
d--------x  5 root   root   4096 Aug 30 10:21 folder1
drwxrwxrwx  2 mysite mysite 4096 Aug 30 09:41 folder2

My question:

How can I mod all files within a specified directory at once? I want to differentiate different chmod settings between directories and folders as well. This needs to be a PHP solution.

This is as far as I can get

<?php

    function modAll($root) {
        
        $aPath = explode("/", $root);
        
        $user = $aPath[2];
        
        /* Some sort of looping through $root */ {
            
            $mod = (is_dir($thisfileorfolder) ? 0755 : 0644);
                    
            chmod($thisfileorfolder, $mod);
            chown($thisfileorfolder, $user);
            chgrp($thisfileorfolder, $user);
        }
    }
    
?>
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

This should be helpful. EDITED: some syntax errors corrected

    function fsmodify($obj) {
       $chunks = explode('/', $obj);
       chmod($obj, is_dir($obj) ? 0755 : 0644);
       chown($obj, $chunks[2]);
       chgrp($obj, $chunks[2]);
    }


    function fsmodifyr($dir) 
    {
       if($objs = glob($dir."/*")) {        
           foreach($objs as $obj) {
               fsmodify($obj);
               if(is_dir($obj)) fsmodifyr($obj);
           }
       }

       return fsmodify($dir);
    }   

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

1.4m articles

1.4m replys

5 comments

56.9k users

...