What are the potential security risks associated with using URLs instead of server directories in file operations in PHP?

When using URLs instead of server directories in file operations in PHP, there is a potential security risk of allowing users to access files outside of the intended directory. To mitigate this risk, it is recommended to validate and sanitize user input to ensure that only allowed directories and files are accessed.

// Validate and sanitize user input for file operations
$allowedDirectories = ['/path/to/allowed/directory1', '/path/to/allowed/directory2'];
$userInput = $_GET['file'];

if (in_array(dirname($userInput), $allowedDirectories)) {
    // Perform file operations
    $fileContents = file_get_contents($userInput);
    echo $fileContents;
} else {
    echo "Access denied";
}