What are the potential consequences of not properly handling file paths in PHP functions like file_get_contents?

Improper handling of file paths in PHP functions like file_get_contents can lead to security vulnerabilities such as directory traversal attacks. To prevent this, it is important to sanitize and validate user input before using it in file operations. One way to do this is by using the realpath() function to resolve the full path of a file and ensure it is within a safe directory.

$file = '/path/to/file.txt';
$realPath = realpath($file);

if ($realPath && strpos($realPath, '/safe/directory/') === 0) {
    $contents = file_get_contents($realPath);
    // Process file contents
} else {
    // Handle invalid file path
}