CORS in PHP: How to Allow Your Front-End to Call Your API Safely

Configuring CORS in a PHP API for a front-end on another domain

Quick answer: A CORS error is the browser blocking a request from one origin to another; your PHP API has to allow that origin in its response headers. Send Access-Control-Allow-Origin with the exact front-end origin (never * when credentials are involved), list the allowed methods and headers, and answer the preflight OPTIONS request with 204 before any authentication runs. CORS is not a security layer for your API: keep validating tokens on the server.

If you have a PHP API and a front-end on another domain or port, you have probably seen this in the browser console:

Access to fetch at 'https://api.example.com/users' from origin 'https://app.example.com'
has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present
on the requested resource.

The request may even have reached your server and returned 200: the browser refused to give the response to your JavaScript. This guide explains why, and how to configure PHP correctly.

What is CORS?

Browsers follow the same-origin policy: JavaScript from one origin can't read responses from another origin unless that server explicitly allows it. An origin is the combination of scheme, host and port, so these are all different origins:

  • https://example.com and https://api.example.com (different host);
  • http://localhost:3000 and http://localhost:8000 (different port);
  • http://example.com and https://example.com (different scheme).

CORS (Cross-Origin Resource Sharing) is how the server says "this origin is allowed". It only applies to browsers: Postman, curl, mobile apps and server-to-server calls ignore it completely, which is why the API "works in Postman" but not in the browser.

Simple requests and preflight requests

For some requests the browser first sends an OPTIONS request, the preflight, asking whether the real request is allowed. This happens when the request:

  • uses PUT, PATCH or DELETE;
  • sends an Authorization header (for example a Bearer token);
  • sends Content-Type: application/json;
  • sends any custom header.

In practice, almost every API call from a modern front-end triggers a preflight. If the OPTIONS request fails, gets a 401, or lacks the CORS headers, the real request is never sent.

A correct CORS setup in PHP

Put this at the very top of the API's entry point (index.php or the front controller), before authentication and before any output:

<?php

$allowedOrigins = [
    'https://app.example.com',
    'https://www.example.com',
    'http://localhost:5173',   // development only: remove in production
];

$origin = $_SERVER['HTTP_ORIGIN'] ?? '';

if (in_array($origin, $allowedOrigins, true)) {
    header('Access-Control-Allow-Origin: ' . $origin);
    header('Access-Control-Allow-Credentials: true');   // only if you use cookies
}
header('Vary: Origin');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    header('Access-Control-Allow-Methods: GET, POST, PUT, PATCH, DELETE, OPTIONS');
    header('Access-Control-Allow-Headers: Content-Type, Authorization');
    header('Access-Control-Max-Age: 86400');            // cache the preflight for a day
    http_response_code(204);
    exit;
}

// authentication, routing and the rest of the API come after this

What each part does:

  • Allowlist: the API echoes back the request's origin only if it is on your list. Unknown origins get no CORS header, so the browser blocks them;
  • Vary: Origin: tells caches and CDNs that the response changes per origin, so one site's response isn't served to another;
  • Preflight first: OPTIONS is answered with 204 and no body, before authentication. Browsers never send the Authorization header in a preflight, so if your auth check runs first, every preflight gets a 401;
  • Max-Age: lets the browser skip the preflight for a while, saving a round trip on every call.

Why not Access-Control-Allow-Origin: *?

The wildcard allows any site to read your API's responses from a visitor's browser. It is acceptable for truly public, read-only data (a public list of products, for example). But:

  • it doesn't work with credentials: browsers reject * together with Access-Control-Allow-Credentials: true;
  • for anything private, you want to control which front-ends can use the API.

Also avoid the shortcut of copying the Origin header back for every request without checking it: that is a wildcard in disguise, and with credentials it lets any site act on behalf of your logged-in users.

CORS with a Bearer token

If the front-end sends Authorization: Bearer ..., the preflight must allow that header:

header('Access-Control-Allow-Headers: Content-Type, Authorization');

Without it, the browser stops before your PHP ever sees the token. On the front-end:

const response = await fetch('https://api.example.com/users', {
    headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
    }
});

CORS with cookies (credentials)

If your API uses a session cookie, the front-end must send credentials:

fetch('https://api.example.com/me', { credentials: 'include' });

And the API must answer with the exact origin plus Access-Control-Allow-Credentials: true. The cookie also needs SameSite=None; Secure to be sent cross-site, which means HTTPS. When possible, putting the API on a subdomain of the same site (api.example.com for app.example.com) avoids many of these problems.

Reading custom response headers

By default, JavaScript can only read a few response headers. If the front-end needs others (for example pagination totals), expose them:

header('Access-Control-Expose-Headers: X-Total-Count');

Common CORS mistakes in PHP

  • Headers only on success: if a 401, 422 or 500 response has no CORS header, the browser hides the real error and shows a CORS error instead. Send the CORS headers at the top, so every response has them;
  • Authentication before the preflight: OPTIONS gets a 401 and nothing works;
  • Headers sent twice: Apache, Nginx or a CDN adds CORS headers and PHP adds them again; browsers reject duplicate Access-Control-Allow-Origin values. Configure CORS in one place only;
  • A PHP warning before the headers: output breaks header() calls; see headers already sent in PHP;
  • A trailing slash or wrong scheme in the allowlist: https://app.example.com/ doesn't match the origin https://app.example.com.

CORS is not authentication

CORS only controls which browser origins can read responses. Anyone can still call your API directly with curl or a script. Always validate tokens, sessions or API keys on the server, check permissions, and limit request rates. See 401 vs. 403 in PHP APIs and JWT authentication in PHP.

Checklist

  • CORS headers sent at the top, before authentication and any output;
  • Origins checked against an allowlist;
  • Vary: Origin sent;
  • OPTIONS answered with 204 and the allowed methods and headers;
  • Authorization allowed when using Bearer tokens;
  • No * with credentials;
  • CORS configured in one place only (PHP or the web server, not both);
  • Authentication still validated on every request.

Conclusion

CORS errors come from the browser, but the fix is in the API's response headers: allow your own origins, answer the preflight before authentication, and send the headers on every response, including errors. With that in place, the front-end can call the API from another domain, and the API stays protected by its own authentication. For the API itself, see how to build a REST API in plain PHP.

Frequently asked questions

Why does my API work in Postman but not in the browser?

CORS is enforced only by browsers. Postman and curl don't check it.

Can I fix CORS on the front-end?

No. The API (or a proxy in front of it) must send the headers. On the front-end, you can only avoid cross-origin calls, for example with a development proxy.

Why does the browser send an OPTIONS request?

It is the preflight, sent before requests with JSON bodies, custom headers like Authorization, or methods like PUT and DELETE.

Should I configure CORS in PHP or in Apache/Nginx?

Either works, but only one. PHP gives you more control, such as an origin allowlist.

Why do I get a CORS error when the real problem is a 500?

The error response didn't include CORS headers, so the browser hid it. Send CORS headers before anything else, so every response carries them.

More in PHP