What are the potential pitfalls of directly inserting variables into file paths in PHP?

Directly inserting variables into file paths in PHP can lead to security vulnerabilities such as path traversal attacks or injection attacks. To mitigate these risks, it's important to sanitize and validate user input before using it in file paths. One way to do this is by using functions like realpath() to resolve the full path and ensure it's within the expected directory.

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

// Validate and sanitize the input
if (preg_match('/^[a-zA-Z0-9_\-\.]+$/', $userInput)) {
    $file = realpath('/path/to/files/' . $userInput);
    
    if ($file !== false && strpos($file, '/path/to/files/') === 0) {
        // File path is valid and safe to use
        // Proceed with file operations
    } else {
        // Invalid file path
        echo 'Invalid file path';
    }
} else {
    // Invalid input
    echo 'Invalid input';
}