What alternative methods can be used to protect directories for FTP access in PHP besides .htaccess?

When protecting directories for FTP access in PHP, an alternative method to using .htaccess files is to implement a PHP authentication system. This can be achieved by creating a login form where users must enter a username and password to access the directory. Upon successful authentication, the PHP script can grant access to the directory by checking the credentials provided.

<?php
// Check if the user is authenticated
if (!isset($_SERVER['PHP_AUTH_USER']) || !isset($_SERVER['PHP_AUTH_PW']) || $_SERVER['PHP_AUTH_USER'] != 'username' || $_SERVER['PHP_AUTH_PW'] != 'password') {
    header('WWW-Authenticate: Basic realm="Restricted Area"');
    header('HTTP/1.0 401 Unauthorized');
    echo 'Access Denied';
    exit;
}

// Grant access to the directory
echo 'You have successfully accessed the directory.';
?>