What are the potential security risks associated with using fopen in PHP scripts?

Using fopen in PHP scripts can pose security risks if not properly handled. One common risk is the possibility of allowing arbitrary file access, which can lead to sensitive data exposure or unauthorized file modifications. To mitigate this risk, it is important to validate user input and sanitize file paths before passing them to fopen.

// Example of validating and sanitizing file path before using fopen
$filename = $_GET['file']; // Assume user input from query parameter
$allowed_files = ['file1.txt', 'file2.txt']; // List of allowed files

if (in_array($filename, $allowed_files)) {
    $filepath = 'path/to/files/' . $filename;
    $handle = fopen($filepath, 'r');
    
    // Rest of the code to read or write to the file
} else {
    echo 'Invalid file access';
}