What are some best practices for handling the creation of directories and index files in PHP?

When creating directories and index files in PHP, it is important to ensure that the directories are created if they do not already exist and that the index files are properly handled to prevent unauthorized access to directory contents. One best practice is to check if the directory exists before creating it and to set appropriate permissions on the index files to restrict access.

// Create directory if it does not exist
$directory = 'path/to/directory';
if (!file_exists($directory)) {
    mkdir($directory, 0777, true);
}

// Create index file with appropriate permissions
$indexFile = $directory . '/index.php';
if (!file_exists($indexFile)) {
    file_put_contents($indexFile, '<?php // Silence is golden.');
    chmod($indexFile, 0644);
}