How can one protect a text file using htaccess but still allow access through PHP?

To protect a text file using htaccess but still allow access through PHP, you can use htaccess to deny direct access to the text file while allowing PHP scripts to access it. You can achieve this by adding a rule in your htaccess file to deny access to the text file from external requests, and then use PHP to read and output the contents of the text file within your script.

<?php
$file = 'protected.txt';

// Check if the file exists
if (file_exists($file)) {
    // Read and output the contents of the text file
    $contents = file_get_contents($file);
    echo $contents;
} else {
    echo 'File not found.';
}
?>