What is the difference between using PHP as a module or CGI in terms of authentication?

When using PHP as a module, authentication is typically handled by the web server, such as Apache, which can use its own authentication mechanisms like .htaccess files. On the other hand, when using PHP as CGI, authentication needs to be handled within the PHP script itself using PHP's built-in functions or by interacting with the web server's authentication mechanisms through environment variables.

// Example of handling authentication in PHP script when using PHP as CGI
$user = 'admin';
$pass = 'password';

if (!isset($_SERVER['PHP_AUTH_USER']) || $_SERVER['PHP_AUTH_USER'] != $user || $_SERVER['PHP_AUTH_PW'] != $pass) {
    header('WWW-Authenticate: Basic realm="Restricted Area"');
    header('HTTP/1.0 401 Unauthorized');
    echo 'Access Denied';
    exit;
}

// Continue with the rest of the script if authentication is successful