What are best practices for setting file permissions in PHP to avoid errors like "Permission denied"?

When working with files in PHP, it is important to set appropriate file permissions to avoid errors like "Permission denied". One way to do this is by using the chmod() function to set the desired permissions on the file or directory. It is also important to ensure that the file or directory is owned by the correct user and group to prevent permission issues.

// Set file permissions to avoid "Permission denied" errors
$filename = 'example.txt';
$permissions = 0644; // Set appropriate permissions (e.g. read and write for owner, read for group and others)

if (file_exists($filename)) {
    chmod($filename, $permissions);
    echo "File permissions set successfully.";
} else {
    echo "File does not exist.";
}