We help IT Professionals succeed at work.

PHP CHOWN Script

Hi Guys

I wonder if someone can help me.

I need a script that iteratively changes any files/directories owned by Apache to the FTP username so that files can be manipulated.

I dont have root access but I understand you can do this using the CHOWN command.

We've found out that we can stop this in the future by setting up the domain differently but I have a live site that needs to be updated in this way.

Clearly I wouldnt leave the script on once completed but was hoping someone had already had this issue with Joomla/Magento installations.

Thanks in advance.
Comment
Watch Question

Top Expert 2013
Commented:
I think you should be able to mount this on a page so it runs off the server.  Don't leave it on the server because in the wrong hands it would be dangerous.

<?php
function Change_Owner($path, $uid)
{
    $thedir = opendir ($path) ;
    while(($file = readdir($thedir)) !== false)
    {
        if ($thefile != "." && $thefile != "..") 
        {
            $thepath = $path . "/" . $file ;
            if (filetype ($thepath) == 'dir') 
            {
                Change_Owner ($thepath, $uid);
            }
            chown($thepath, $uid);
            /* 
            It is a good idea to log $thepath as they are changed, or at least 
            display it on the screen with an echo so you can verify what is changed
            */
        }
    }

 }
?>

Open in new window



Cd&
Most Valuable Expert 2011
Top Expert 2016

Commented:
I think CD& has a good answer for you.  You might also be able to do something like this:

chmod ($my_file, 0777);

Author

Commented:
Hi Guys

Thanks for your comments thus far. Will the script iterate down through directories or will I have to run it for each directory?

Thanks
Top Expert 2013

Commented:
This bit causes it to call a new copy of the function to drill down trough directories so a single run starting from the top level directory should handle it all the way down:

if (filetype ($thepath) == 'dir')
            {
                Change_Owner ($thepath, $uid);
            }

Cd&

Author

Commented:
Thats great, if I leave the path blank , i.e. '' then will it start from wherever file is located and work down through the tree? Like this ...

<?php
function Change_Owner($path, $uid)
{
    $thedir = opendir ($path) ;
    while(($file = readdir($thedir)) !== false)
    {
        if ($thefile != "." && $thefile != "..")
        {
            $thepath = $path . "/" . $file ;
            if (filetype ($thepath) == 'dir')
            {
                Change_Owner ($thepath, $uid);
            }
            echo "Changing '".$thepath."' to be owned by '".$uid."'";
          chown($thepath, $uid);
            echo " .. done!";
          echo "<br>";
        }
    }

 }
Change_Owner("","newowner");
?>

Thanks again!

Author

Commented:
Thanks Guys, well sorted.