Saturday, October 29, 2022

[SOLVED] Set chmod for full path in PHP

Issue

I have input path: /var/www/site.com/1/2/3/4/file.php

I want to: set chmod 755 on each element after /var/www/site.com/

e.g. do that by universal algorithm:

chmod ('/var/www/site.com/1/', 0755);
chmod ('/var/www/site.com/1/2/', 0755);
chmod ('/var/www/site.com/1/2/3/', 0755);
chmod ('/var/www/site.com/1/2/3/4/', 0755);
chmod ('/var/www/site.com/1/2/3/4/file.php', 0755);

Can you help me, Please?

P.S.: Just only chmod full path, not recursive.


Solution

<?php
function chmod_path($base, $path, $perm) {
    $full_path = $base;
    foreach (explode(DIRECTORY_SEPARATOR, $path) as $dentry) {
        $full_path .= DIRECTORY_SEPARATOR.$dentry;
        chmod($full_path, $perm);
    }
}

chmod_path('/var/www/site.com', '1/2/3/4/file.php', 0755);
?>


Answered By - Greg Bowser
Answer Checked By - Senaida (WPSolving Volunteer)