What are the best practices for creating directories in PHP using mkdir() function?

When creating directories in PHP using the mkdir() function, it is important to follow best practices to ensure the directory is created successfully and securely. Some best practices include specifying the correct permissions for the directory, checking if the directory already exists before creating it, and handling any errors that may occur during the creation process.

$directory = 'path/to/directory';

if (!file_exists($directory)) {
    if (!mkdir($directory, 0777, true)) {
        die('Failed to create directory');
    }
    echo 'Directory created successfully';
} else {
    echo 'Directory already exists';
}