What are the potential security risks associated with using PHP to open files from a directory specified by a user?

When using PHP to open files from a directory specified by a user, there is a risk of directory traversal attacks where an attacker can manipulate the input to access files outside of the intended directory. To prevent this, it is important to validate and sanitize user input before using it to open files.

$directory = '/path/to/directory/';
$userInput = $_GET['file'];

// Validate and sanitize user input
$filePath = realpath($directory . $userInput);

if (strpos($filePath, $directory) !== 0) {
    die('Invalid file path');
}

$fileContent = file_get_contents($filePath);
echo $fileContent;