What are the best practices for opening PDF files from a network drive in PHP without compromising security?

When opening PDF files from a network drive in PHP, it is important to handle the file path securely to prevent any potential security risks such as directory traversal attacks. One way to do this is by using the realpath() function to resolve the file path to its absolute path and then verifying that it is within the allowed directory.

$filepath = '/path/to/network/drive/file.pdf';

// Resolve the file path to its absolute path
$realpath = realpath($filepath);

// Check if the resolved path is within the allowed directory
$allowed_directory = '/path/to/allowed/directory/';
if (strpos($realpath, $allowed_directory) !== 0) {
    die('Access denied');
}

// Open the PDF file
if (file_exists($realpath)) {
    header('Content-type: application/pdf');
    readfile($realpath);
} else {
    die('File not found');
}