What are best practices for preventing direct access to files in PHP?

To prevent direct access to files in PHP, it is recommended to place sensitive files outside of the web root directory and use PHP to read and serve the files as needed. This helps to ensure that files cannot be accessed directly by users through a browser.

<?php
// Prevent direct access to files by checking if a specific constant is defined
if (!defined('MY_APP')) {
    header('HTTP/1.0 403 Forbidden');
    die('Direct access not allowed');
}

// Code to serve the file content here