How can you handle errors or exceptions when working with file and directory creation in PHP?

When working with file and directory creation in PHP, it is important to handle errors or exceptions that may occur during the process. One way to do this is by using try-catch blocks to catch any exceptions that are thrown and handle them accordingly. This allows you to gracefully handle errors and prevent your script from crashing.

try {
    // Attempt to create a directory
    if (!mkdir('/path/to/directory', 0777, true)) {
        throw new Exception('Failed to create directory');
    }

    // Attempt to create a file
    if (!file_put_contents('/path/to/file.txt', 'Hello, World!')) {
        throw new Exception('Failed to create file');
    }
} catch (Exception $e) {
    // Handle the exception
    echo 'An error occurred: ' . $e->getMessage();
}