The HTTP 401 Unauthorized error indicates that the server requires user authentication to access a resource. When a user attempts to access protected content without proper credentials, this error is returned. This article summarizes common causes of 401 errors in PHP and provides corresponding solutions.
If the server has not configured authentication, users cannot access protected resources.
You can set the authentication type using PHP's header() function:
header('WWW-Authenticate: Basic realm="My Realm"');If the username or password provided by the user does not match the information stored on the server, access will fail.
Check whether the user's credentials are correct or guide the user to reset their password.
401 errors can also occur if the user does not have permission to access the protected file.
Ensure the file permissions are correctly set so that users have the appropriate access rights.
On Apache servers, the .htaccess file is used to configure authentication. If it is missing in the directory, the server cannot perform authentication.
Create a .htaccess file in the protected directory and include authentication configuration:
AuthType Basic
AuthName "My Realm"
AuthUserFile /path/to/auth-file
Require valid-userIncorrect server configuration or technical issues may also cause HTTP 401 errors.
Check server logs for error messages and contact technical support if needed.
Suppose there is a protected folder private containing a password-protected file secret.txt. You can use the following PHP code to set up authentication:
<!--?php
// Set up basic authentication
header('WWW-Authenticate: Basic realm="My Realm"');
// Check credentials
if (isset($_SERVER['PHP_AUTH_USER']) && isset($_SERVER['PHP_AUTH_PW'])) {
    // Read users and passwords from file
    $users = file("users");
    $authenticated = false;
    foreach ($users as $line) {
        list($username, $password) = explode(":", trim($line));
        // Compare provided credentials with file
        if ($_SERVER['PHP_AUTH_USER'] == $username && $_SERVER['PHP_AUTH_PW'] == $password) {
            $authenticated = true;
            break;
        }
    }
    // Allow access if authenticated
    if ($authenticated) {
        fopen("private/secret.txt", "r");
    } else {
        // Not authenticated, return error
        header('HTTP/1.0 401 Unauthorized');
        echo 'Authentication failed.';
    }
} else {
    // Credentials not available, request authentication
    header('HTTP/1.0 401 Unauthorized');
    echo 'Authorization Required.';
}
?-->With this setup, you can effectively manage access to protected resources in PHP and prevent HTTP 401 Unauthorized errors from affecting user experience.