401 vs. 403 in PHP APIs: The Difference, Common Causes and How to Fix Them

Difference between 401 Unauthorized and 403 Forbidden in PHP APIs

Quick answer: 401 Unauthorized means the request isn't authenticated: the token is missing, invalid or expired. 403 Forbidden means it is authenticated, but the user isn't allowed to do that. In a PHP API, validate the token first (fail: 401), then the permission (denied: 403). If every request gets 401 even with a valid token, check whether Apache is dropping the Authorization header, and whether the preflight OPTIONS request is hitting your auth check.

401 and 403 are among the most common errors in REST APIs, and among the most misused. They look similar, but they mean different things, and returning the wrong one makes debugging harder for the front-end, mobile apps and integrations.

401 vs. 403 at a glance

StatusMeaningQuestion it answersWhat the client should do
401 UnauthorizedNot authenticatedWho are you?Log in again or refresh the token
403 ForbiddenAuthenticated, but not allowedAre you allowed to do this?Don't retry; show "access denied"

The names are confusing: "Unauthorized" actually means unauthenticated. A simple way to remember: 401 is about identity, 403 is about permission.

401 Unauthorized

When to return it

  • No Authorization header;
  • A token in the wrong format;
  • An invalid signature;
  • An expired token;
  • A revoked token or a deleted user.

According to the HTTP specification, a 401 response should include a WWW-Authenticate header saying which scheme to use.

Reading the Bearer token

<?php

function getBearerToken(): ?string
{
    $header = $_SERVER['HTTP_AUTHORIZATION']
        ?? $_SERVER['REDIRECT_HTTP_AUTHORIZATION']
        ?? '';

    if ($header === '' && function_exists('getallheaders')) {
        $headers = array_change_key_case(getallheaders(), CASE_LOWER);
        $header = $headers['authorization'] ?? '';
    }

    if (preg_match('/^Bearer\s+(\S+)$/i', $header, $m)) {
        return $m[1];
    }

    return null;
}

function unauthorized(string $message): never
{
    http_response_code(401);
    header('WWW-Authenticate: Bearer');
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode(['success' => false, 'message' => $message]);
    exit;
}

$token = getBearerToken();

if ($token === null) {
    unauthorized('Authentication required.');
}

// validate the JWT signature and expiry here; on failure:
// unauthorized('Invalid or expired token.');

The most common hidden cause: Apache drops the Authorization header

When PHP runs as CGI or FastCGI (PHP-FPM) behind Apache, the Authorization header is often not passed to PHP, so $_SERVER['HTTP_AUTHORIZATION'] is empty and every request gets 401, even with a valid token. Fix it in the .htaccess or the virtual host:

# Apache 2.4.13 and newer
CGIPassAuth On

# Alternative with mod_rewrite
RewriteEngine On
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

To confirm the diagnosis, log what PHP receives: error_log(print_r(getallheaders(), true));. If Authorization isn't there, the server is dropping it.

403 Forbidden

When to return it

  • A regular user calling an admin-only endpoint;
  • A user trying to read or change another user's data;
  • An account that is suspended or hasn't confirmed its email;
  • A plan or feature the user hasn't paid for.
<?php

function forbidden(string $message = 'You do not have permission to do this.'): never
{
    http_response_code(403);
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode(['success' => false, 'message' => $message]);
    exit;
}

// role check
if ($user['role'] !== 'admin') {
    forbidden();
}

// ownership check: can this user edit this order?
if ((int) $order['user_id'] !== (int) $user['id'] && $user['role'] !== 'admin') {
    forbidden();
}

The ownership check is the one most often forgotten. Without it, any logged-in user can change the ID in the URL and read other people's data.

403 or 404?

When a user asks for a resource that belongs to someone else, many APIs return 404 instead of 403, so they don't reveal that the record exists. Both are valid choices; be consistent across the API.

The right order of checks

  1. Answer OPTIONS preflight requests (CORS) without authentication;
  2. Authenticate: missing or invalid token gives 401;
  3. Authorize: no permission gives 403;
  4. Validate the input: invalid data gives 422;
  5. Run the action.
<?php

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(204);
    exit;
}

$user = authenticate();               // calls unauthorized() on failure

if (!userCan($user, 'orders.edit')) { // your permission check
    forbidden();
}

// validate input, then do the work

401 and CORS: a classic false alarm

Browsers send a preflight OPTIONS request before calls with an Authorization header, and the preflight never includes the token. If your API authenticates OPTIONS too, it returns 401, and the browser blocks the real request with a CORS error. Answer the preflight before authentication, as above. See CORS in PHP.

How the client should react

Returning 401 for a permission problem makes clients refresh tokens or log users out for no reason; returning 403 for an expired token stops them from refreshing.

401/403 from the web server instead of your code

If the response is an HTML error page instead of your JSON, the 401 or 403 came from Apache, Nginx, a WAF or the hosting panel, not from PHP. Typical causes: HTTP Basic Auth on the folder, file permissions, or a security rule. See 403 Forbidden on PHP sites.

Best practices

  • 401 only for authentication, 403 only for permission;
  • Return the same JSON error format for both;
  • Don't reveal details such as "user exists but wrong password";
  • Check ownership of every record, not just roles;
  • Log repeated 401s and 403s: they can reveal attacks or broken clients.

Conclusion

401 answers "who are you?" and 403 answers "are you allowed?". Check them in that order, after the CORS preflight, and return a consistent JSON body for both. When valid tokens still get 401, look at the server first: a dropped Authorization header is the most common culprit in PHP. For a complete error format, see error handling in a PHP API.

Frequently asked questions

What is the difference between 401 and 403?

401: the request isn't authenticated. 403: it is authenticated, but the user isn't allowed to do it.

Should an expired token return 401 or 403?

401. The client should refresh the token or log in again.

Why is $_SERVER['HTTP_AUTHORIZATION'] empty?

Apache often doesn't pass the header to PHP under CGI/FastCGI. Add CGIPassAuth On or the rewrite rule shown above.

Why does my front-end get 401 on OPTIONS requests?

Your API is authenticating the CORS preflight. Answer OPTIONS with 204 before the authentication check.

Should a wrong password return 401?

Yes, a failed login is usually 401, with a generic message such as "invalid email or password".

More in PHP