Why does the chmod function not work as expected when setting directory permissions in PHP?

The issue with the chmod function not working as expected when setting directory permissions in PHP is often due to the fact that PHP runs with a different user/group than the one that owns the directory. To solve this issue, you can use the chown function in combination with chmod to first change the ownership of the directory to the PHP user/group, and then set the desired permissions.

$directory = '/path/to/directory';
$permissions = 0755; // desired permissions

// Change ownership of the directory to the PHP user/group
chown($directory, 'www-data'); // Change 'www-data' to the appropriate user/group

// Set the desired permissions for the directory
chmod($directory, $permissions);