What potential security risks are associated with allowing users to input file paths in PHP scripts?

Allowing users to input file paths in PHP scripts can potentially lead to security risks such as directory traversal attacks, where users can access files outside of the intended directory. To mitigate this risk, it is important to sanitize and validate user input before using it in file operations.

// Sanitize and validate user input for file paths
$userInput = $_POST['file_path'];
$cleanedInput = realpath('uploads/' . $userInput);

// Check if the cleaned input is within the uploads directory
if (strpos($cleanedInput, 'uploads/') !== false) {
    // Proceed with file operations using $cleanedInput
    // For example: file_get_contents($cleanedInput);
} else {
    // Handle invalid file path input
    echo "Invalid file path";
}