What are the potential security risks associated with using user input to define file paths in PHP?

Using user input to define file paths in PHP can lead to security risks such as directory traversal attacks, where an attacker can access sensitive files outside of the intended directory. To mitigate this risk, it is essential to sanitize and validate user input before using it to construct file paths.

// Sanitize and validate user input before using it to define file paths
$userInput = $_POST['file_path']; // Assuming user input comes from a form field

// Validate the user input to ensure it is a valid file path
if (preg_match('/^[a-zA-Z0-9\/]+$/', $userInput)) {
    $filePath = '/path/to/root/directory/' . $userInput; // Construct the file path
    // Use $filePath safely in your PHP code
} else {
    // Handle invalid file path input
}