What is the purpose of preventing direct access to a PHP file via the address bar?

Preventing direct access to a PHP file via the address bar is important for security reasons, as it can help protect sensitive information or functions within the file from being accessed by unauthorized users. One way to prevent direct access is by checking if a specific constant or variable is defined in the file, and if not, redirecting the user to another page.

<?php
if(!defined('MY_CONSTANT')){
    header("Location: index.php");
    exit();
}
// Rest of the PHP code goes here
?>