What are some best practices for handling external file access in PHP applications to avoid security vulnerabilities and server configuration limitations?

When handling external file access in PHP applications, it is important to sanitize user input to prevent directory traversal attacks and ensure that only allowed file types are accessed. Additionally, it is recommended to use absolute file paths instead of relative paths to avoid server configuration limitations. Implementing proper file permissions and using secure file handling functions can also help mitigate security risks.

// Example of sanitizing user input and accessing a file securely

$allowed_file_types = array('jpg', 'png', 'pdf');
$filename = $_GET['file'];

if (preg_match('/^[a-zA-Z0-9]+\.(jpg|png|pdf)$/', $filename) && in_array(pathinfo($filename, PATHINFO_EXTENSION), $allowed_file_types)) {
    $file_path = '/path/to/files/' . $filename;

    if (file_exists($file_path)) {
        // Access the file securely
        $file_contents = file_get_contents($file_path);
        echo $file_contents;
    } else {
        echo 'File not found.';
    }
} else {
    echo 'Invalid file type.';
}