What are the dangers of allowing user input to directly influence file paths in PHP code?

Allowing user input to directly influence file paths in PHP code can lead to security vulnerabilities such as directory traversal attacks, where malicious users can access sensitive files on the server. To prevent this, it is important to sanitize and validate user input before using it to construct file paths.

// Sanitize and validate user input before using it in file paths
$userInput = $_POST['user_input'];

// Example of sanitizing user input by only allowing alphanumeric characters
$sanitizedInput = preg_replace("/[^a-zA-Z0-9]+/", "", $userInput);

// Construct file path using the sanitized input
$filePath = "/path/to/directory/" . $sanitizedInput . ".txt";