How to set chmod for a folder and all of its subfolders and files in PHP?

15,249

Solution 1

chmod("Folder",0770);

function in php allow you to change permission of file and for recursive change use exec

exec ("find /path/to/folder -type d -exec chmod 0770 {} +");//for sub directory
exec ("find /path/to/folder -type f -exec chmod 0644 {} +");//for files inside directory

make sure that your webserver have write access to the Folder.

Check these for more detail
http://php.net/manual/en/function.chmod.php
http://www.w3schools.com/php/func_filesystem_chmod.asp

Solution 2

There's a long winded way to do it in php, I would personally do it via the command line which PHP can interact with.

On the command line (Linux/Unix) you can do chmod options permissions filename

To recursively change permissions you would do chmod -R 0777 masterFile

So in PHP you would do exec("chmod -R 0777 masterFile");

-R means recursive so it would go to your sub-folders

The long winded way to do in PHP alone would be to get an array of the sub folders and do a foreach loop and run the chmod() function in PHP, but this way is cleaner.

See this link for more information on linux/unix chmod

Hope this helps.

Share:
15,249
Parsa P.
Author by

Parsa P.

Updated on June 28, 2022

Comments

  • Parsa P.
    Parsa P. almost 2 years

    I think my question explains everything. I want to use php's chmod() function to set a 777 permission on a folder, its subfolders and files.

    Any Help is appreciated. THX.