What are the best practices for handling username and password authentication when accessing a .json file in PHP?

When accessing a .json file in PHP, it is important to ensure that username and password authentication is implemented to protect sensitive data. One of the best practices for handling this authentication is to use HTTP Basic Authentication, where the username and password are sent in the request headers. This can be done by setting the 'Authorization' header with the base64 encoded username and password.

<?php

$username = 'username';
$password = 'password';

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

// Continue with accessing the .json file
$file = 'data.json';
$data = file_get_contents($file);
$json = json_decode($data, true);

// Use the JSON data as needed