How does PHP handle special characters in file names differently when creating directories compared to when reading them?

When creating directories in PHP, special characters in file names can cause issues such as directory creation failures or unexpected behavior. To handle special characters properly, it's recommended to sanitize the file names before creating directories by removing or replacing special characters with safe alternatives. When reading directories, PHP automatically handles special characters in file names, so no additional steps are required.

// Sanitize file name before creating directory
$unsafeFileName = 'file_with_special_characters.txt';
$safeFileName = preg_replace('/[^\w\-\.]/', '_', $unsafeFileName); // Replace special characters with underscores
$directoryPath = '/path/to/directory/' . $safeFileName;

if (!file_exists($directoryPath)) {
    mkdir($directoryPath);
}