What best practices should be followed when using PHP to create directories to ensure proper functionality and security?

When creating directories in PHP, it is important to follow best practices to ensure proper functionality and security. One key practice is to validate user input to prevent directory traversal attacks. Additionally, always use absolute paths when creating directories to avoid any unexpected behavior. Lastly, make sure to set appropriate permissions on the newly created directories to restrict access as needed.

<?php

// Validate user input to prevent directory traversal attacks
$directory_name = filter_var($_POST['directory_name'], FILTER_SANITIZE_STRING);

// Use absolute paths when creating directories
$base_directory = '/path/to/base/directory/';
$new_directory = $base_directory . $directory_name;

// Create the directory with appropriate permissions
if (!file_exists($new_directory)) {
    mkdir($new_directory, 0755, true);
    echo 'Directory created successfully!';
} else {
    echo 'Directory already exists!';
}

?>