What are common methods to prevent direct access to PHP classes and templates in a web application?

To prevent direct access to PHP classes and templates in a web application, you can use the following methods: 1. Place sensitive files outside the web root directory to prevent direct access. 2. Use .htaccess files to restrict access to specific directories or files. 3. Implement access control checks within your PHP code to verify the user's permissions before serving the content.

// Example of restricting direct access to a PHP file using a check for a constant defined in the main application file

// Define a constant in your main application file
define('MY_APP', true);

// Check for the constant in the included PHP file
if (!defined('MY_APP')) {
    header('HTTP/1.0 403 Forbidden');
    exit;
}

// Your PHP code goes here