Skip to content
PHP Logo

What PHP functions or methods can be used to read and output file contents to users while maintaining security and access control?

When reading and outputting file contents in PHP, it is important to ensure security and access control to prevent unauthorized access to sensitive files on the server. One way to achieve this is by using the file_exists() function to check if the file exists and is accessible, and the is_readable() function to verify if the file is readable. Additionally, you can use the readfile() function to output the file contents to users while preventing direct access to the file by placing the files outside the web root directory or using proper access restrictions.

php
$file = 'path/to/file.txt';

if (file_exists($file) && is_readable($file)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="' . basename($file) . '"');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    readfile($file);
    exit;
} else {
    echo 'File not found or not readable.';
}