How can the use of is_writable and realpath functions help in troubleshooting mkdir errors in PHP scripts?

When encountering mkdir errors in PHP scripts, the use of is_writable and realpath functions can help in troubleshooting by checking if the directory is writable and obtaining the absolute path of the directory, respectively. This can help identify permission issues or incorrect directory paths causing the mkdir function to fail.

$directory = 'path/to/directory';

if (!is_writable(dirname(realpath($directory)))) {
    echo "Directory is not writable or does not exist.";
} else {
    mkdir($directory, 0777, true);
    echo "Directory created successfully.";
}