How can PHP scripts prevent unauthorized access to directories containing sensitive user data, such as using HTTP_AUTH or MOD_REWRITE?

To prevent unauthorized access to directories containing sensitive user data, PHP scripts can utilize HTTP_AUTH or MOD_REWRITE to restrict access based on user credentials or IP addresses. This adds an additional layer of security to prevent unauthorized users from accessing sensitive information.

// Using HTTP_AUTH to restrict access based on user credentials
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;
}

// Using MOD_REWRITE to restrict access based on IP addresses
$allowed_ips = array('192.168.1.1', '10.0.0.1');
if (!in_array($_SERVER['REMOTE_ADDR'], $allowed_ips)) {
    header('HTTP/1.0 403 Forbidden');
    echo 'Access Denied';
    exit;
}