What are the best practices for hiding a PHP script from direct access?

To hide a PHP script from direct access, you can place the script outside of the web root directory or use an .htaccess file to deny access to the script. Another option is to check if a constant is defined in the script and exit if it is not, ensuring that the script can only be accessed if included in another file.

<?php
// Check if a specific constant is defined
if (!defined('MY_SECRET_CONSTANT')) {
    // Exit if constant is not defined
    exit('Direct script access denied');
}

// Your PHP script code goes here
echo 'This script is protected from direct access';