What are the best practices for checking directory permissions in PHP before writing a file?

When writing files in PHP, it is important to check the directory permissions to ensure that the script has the necessary permissions to write the file. This can help prevent issues such as permission denied errors or security vulnerabilities. One way to check directory permissions is by using the `is_writable()` function in PHP, which checks if a directory is writable by the script.

$directory = 'path/to/directory';

if (!is_writable($directory)) {
    echo "Directory is not writable. Please check permissions.";
    exit;
}

// Proceed with writing file to directory