How can PHP handle errors related to directory creation and permission changes?

When creating directories or changing permissions in PHP, errors can occur due to insufficient permissions or incorrect paths. To handle these errors, you can use PHP's error handling functions like try-catch blocks or checking the return value of directory creation and permission change functions.

<?php
$dir = 'new_directory';

// Attempt to create the directory
if (!mkdir($dir, 0777) && !is_dir($dir)) {
    throw new Exception('Failed to create directory');
}

// Attempt to change directory permissions
if (!chmod($dir, 0777)) {
    throw new Exception('Failed to change directory permissions');
}

echo 'Directory created and permissions changed successfully';
?>