What are some potential security risks when directly accessing files in PHP, and how can they be mitigated?

One potential security risk when directly accessing files in PHP is the possibility of exposing sensitive information or allowing malicious users to manipulate files on the server. To mitigate this risk, it is important to validate user input, sanitize file paths, and restrict access to only necessary files and directories.

// Example of mitigating security risks when accessing files in PHP

$filename = $_GET['filename'];

// Validate user input
if (preg_match('/^[a-zA-Z0-9_]+\.[a-zA-Z]{3,4}$/', $filename)) {
    $filepath = 'uploads/' . $filename;

    // Sanitize file path
    $filepath = realpath($filepath);

    // Restrict access to necessary files and directories
    if (strpos($filepath, 'uploads/') === 0) {
        // Access the file
        $file_contents = file_get_contents($filepath);
    } else {
        echo 'Access denied';
    }
} else {
    echo 'Invalid filename';
}