What is the potential issue with using variables in file paths with file_get_contents in PHP?

When using variables in file paths with file_get_contents in PHP, there is a potential security risk known as directory traversal or path traversal attack. An attacker may manipulate the variable to access sensitive files outside of the intended directory. To prevent this issue, it is important to sanitize and validate the input to ensure that the file path is within the expected directory.

// Sanitize and validate the input file path before using it with file_get_contents
$filePath = "/path/to/directory/" . basename($_GET['file']);
if (strpos($filePath, '/path/to/directory/') === 0 && file_exists($filePath)) {
    $fileContent = file_get_contents($filePath);
    // Process the file content
} else {
    // Handle invalid file path
}