How can .htaccess be used to restrict access to a specific directory only for server-side scripts like PHP?

To restrict access to a specific directory only for server-side scripts like PHP, you can use the .htaccess file to set up authentication. This will require users to enter a username and password before they can access the directory. This is useful for protecting sensitive files or scripts from unauthorized access.

<?php
// .htaccess file content
$htpasswd = '/path/to/.htpasswd';
$realm = 'Restricted Area';

$users = array('username' => 'password');

if (!in_array($_SERVER['PHP_AUTH_USER'], array_keys($users)) || $users[$_SERVER['PHP_AUTH_USER']] != $_SERVER['PHP_AUTH_PW']) {
    header('WWW-Authenticate: Basic realm="'.$realm.'"');
    header('HTTP/1.0 401 Unauthorized');
    echo 'Access Denied';
    exit;
}
?>