How can a PHP file be protected from direct access and only be included in other files?

To protect a PHP file from direct access and only allow it to be included in other files, you can use a conditional check to ensure that the file is being included and not accessed directly. This can be done by checking if a specific constant is defined in the file and if it is not, then the script should exit.

<?php
// Check if a specific constant is defined
if(!defined('INCLUDED_FROM_MAIN_FILE')){
    // If not defined, exit the script
    exit('Direct script access not allowed');
}
// Rest of the code here