Php Warning: chmod(): Operation not permitted

57 Views Asked by At

I have an error with php function chmod https://www.php.net/manual/en/function.chmod.php Any solutions? I'm running Linux Debian 13.05 with root access and PHP 8.2. Php Warning: chmod(): No such file or directory in file: index.php on line: 8 After I added a empty file, I we get:

Php Warning: chmod(): Operation not permitted in file: index.php on line: 8 Php Warning: fopen(./access.log): Failed to open stream: Permission denied in file: index.php on line: 9

$root_path = './'; define('LOG_FILE', $root_path . 'access.log');

function add_log_entry($access = '')
{
    if (LOG_FILE)
    {
        chmod(LOG_FILE, 0755);
        $fopen = fopen(LOG_FILE, 'ab');
    }
}   
1

There are 1 best solutions below

2
FlorinCB On

This is working if the directory and file is created by same user in '/var/www/myphpapp/' and from same user group and can be continued until there that we do not need to use 'sudo chmod -R 777 /var/www/html/myphpapp' nor ftp chmod command. Another solution on Linux is to use a subdirectory in our own '/home/user/www/' directory, or in '/root/www/' for given example, and this can be simplified.

$root_path = './'; 
define('LOG_FILE', $root_path . 'access.log');
    
    function add_log_entry($access = '')
    {
        if (LOG_FILE)
        {
            // Default to write
            $perms = 2;
            
            // Add read/write and execute bit to owner among perms
            $owner_perm = (4 | 2) | (1);
            $file_perm  = ($owner_perm << 6) + ($perms << 3) + ($perms << 0);

            // Compute directory permissions, 7 is for all
            $perm = ($perms !== 0) ? ($perms | 1) : $perms;
            $dir_perm = (($owner_perm | 1) << 6) + ($perm << 3) + ($perm << 0);
    
            // Don't chmod links as mostly those require 0777 and that cannot be changed
            if (is_dir(LOG_FILE) || (is_link(LOG_FILE)))
            {
                if (true !== @chmod(LOG_FILE, $dir_perm))
                {
                    print('Filesystem_cannot_change_access_log_file_permissions.');
                }
            }
            else if (is_file(LOG_FILE))
            {
                if (true !== @chmod(LOG_FILE, $file_perm))
                {
                    print('Filesystem_cannot_change_access_log_file_permissions.');
                }
            }
            
            $fopen = @fopen(LOG_FILE, 'ab'); //add more code
        }
    }