Are there any best practices for creating folders and files dynamically in PHP based on user input?

When creating folders and files dynamically in PHP based on user input, it is important to sanitize and validate the user input to prevent any security vulnerabilities such as directory traversal attacks. It is also recommended to set appropriate permissions on the newly created folders and files to ensure they are secure. Additionally, using unique identifiers or timestamps in the folder or file names can help avoid conflicts.

<?php

// Sanitize and validate user input
$userInput = $_POST['input'];
$cleanInput = filter_var($userInput, FILTER_SANITIZE_STRING);

// Create a unique folder name based on user input
$folderName = uniqid() . '_' . $cleanInput;

// Create the folder
if (!file_exists($folderName)) {
    mkdir($folderName, 0755);
    echo "Folder created successfully!";
} else {
    echo "Folder already exists!";
}

// Create a file inside the folder
$fileContent = "Hello, World!";
$filePath = $folderName . '/example.txt';
file_put_contents($filePath, $fileContent);

// Set appropriate permissions on the folder and file
chmod($folderName, 0755);
chmod($filePath, 0644);

?>