What are potential security risks when automatically creating folders and editing files based on user input in PHP?

Potential security risks when automatically creating folders and editing files based on user input in PHP include directory traversal attacks, allowing users to access sensitive files on the server, and code injection vulnerabilities if the user input is not properly sanitized. To mitigate these risks, it is crucial to validate and sanitize user input before using it to create folders or edit files.

// Sanitize user input before creating folders or editing files
$userInput = $_POST['input'];
$sanitizedInput = filter_var($userInput, FILTER_SANITIZE_STRING);

// Create folder based on sanitized user input
$folderPath = 'uploads/' . $sanitizedInput;
if (!file_exists($folderPath)) {
    mkdir($folderPath, 0777, true);
}

// Edit file based on sanitized user input
$fileContent = 'Content edited by user: ' . $sanitizedInput;
$file = fopen('file.txt', 'w');
fwrite($file, $fileContent);
fclose($file);