Change File Permissions and Owner of a Staging Site

Some hosting setups use an unusual configuration of the owner and permissions of a WordPress website.

For example, your hosting setup may use PHP-FPM that runs as the user account, so when PHP accesses the file system, it creates files under its own name. WordPress, on the other hand, might require different permissions that lead to images uploaded to the gallery under the web server name. So, after creating a staging site, you can get permission errors.

WP Staging creates a staging site with the default WordPress permissions of 755 for files and 644 for folders. The owner is the user of the PHP process that created the staging site.

To fix this you can change the owner and permissions of a staging site after creating one by using this function and filter:

PHP
<?php

function changePermissionsAndOwner() {

$directory = '/path/to/your/directory';
$permissions = 0755;
$owner = 'username';
$group = 'groupname';

    // Check if the path is a directory
    if (is_dir($path)) {
        // Create a RecursiveDirectoryIterator object
        $directoryIterator = new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::SKIP_DOTS);
        // Create a RecursiveIteratorIterator object
        $iterator = new RecursiveIteratorIterator($directoryIterator, RecursiveIteratorIterator::SELF_FIRST);

        // Iterate through each file and directory in the tree
        foreach ($iterator as $item) {
            // Change the permissions of the current item
            chmod($item, $permissions);
            // Change the owner and group of the current item
            chown($item, $owner);
            chgrp($item, $group);
        }

        // Change the permissions of the root directory
        chmod($path, $permissions);
        // Change the owner and group of the root directory
        chown($path, $owner);
        chgrp($path, $group);
    } else {
        echo "The path is not a directory.";
    }
}

add_action('wpstg.clone_first_run', 'changePermissionsAndOwner', 10);

This will run on the first login to the staging site and change all files to the corresponding permissions.

Updated on July 18, 2024