In this chapter
We'll take a first look at two browser security rules every PHP developer meets: the same-origin policy and CORS, which decides whether JavaScript on another site may read your responses, and CSRF, where another site makes a visitor's browser send requests to yours — and how SameSite cookies and CSRF tokens stop it.
The Problem in Real Life
The web designer building www.tomsbarbershop.co.uk wants to show BookBay's free slots on Tom's own homepage with a few lines of JavaScript. The browser console says: "Access to fetch at 'https://bookbay.app/api/slots' from origin 'https://www.tomsbarbershop.co.uk' has been blocked by CORS policy".
Meanwhile Marcus writes a tiny test page on his own laptop's site, with a hidden form that POSTs to BookBay's cancel.php as soon as it loads. With the barber logged in to BookBay in another tab, opening that page cancels booking 4811.
One rule stops other sites from reading our data. Nothing stops them from sending us requests — unless we check.
Marcus
Trusting the Browser vs. Knowing What It Does and Doesn't Protect
Same-origin policy
JavaScript may only read responses from its own origin — unless the server allows it with CORS.
Forged requests
Another site can make a logged-in visitor's browser submit your forms.
A secret per form
A CSRF token proves the form came from your own page.
CORS and CSRF: A First Look
Two rules about other websites: both CORS and CSRF are about requests that involve another site. They're often confused; they protect against different things. This chapter covers:
- Origins: and the same-origin policy.
- CORS: allowing another site's JavaScript to read your responses.
- Preflight requests: OPTIONS before the real request.
- CSRF: forged requests, and why cookies make them work.
- Defences: SameSite cookies and CSRF tokens.
Origins and the same-origin policy: an origin is the combination of scheme, host and port: https://bookbay.app and https://www.tomsbarbershop.co.uk are different origins, and so are http:// and https:// of the same host. Browsers apply the same-origin policy: JavaScript running on one origin may send requests to another, but may not read the response — otherwise any website you visit could read your webmail through your logged-in browser. The policy protects the visitor, and it's enforced by the browser: curl, PHP scripts and mobile apps don't care about it.
CORS: Cross-Origin Resource Sharing lets your server say "this other origin may read my responses". It does it with response headers: Access-Control-Allow-Origin: https://www.tomsbarbershop.co.uk (one exact origin, or * for public data without cookies), plus Vary: Origin when the answer depends on the Origin request header. In PHP that's a few header() calls; compare the Origin header with an allow-list — never echo back whatever origin was sent. The real output below shows the difference: the allowed origin gets the header; another origin gets the data but no header, so its browser refuses to hand it to the JavaScript. Note what that means: CORS isn't a server-side lock. Anyone can still call the URL directly; protect private data with authentication, not CORS.
<?php// public/api/slots.phpconst ALLOWED_ORIGINS = ['https://www.tomsbarbershop.co.uk'];$origin = $_SERVER['HTTP_ORIGIN'] ?? '';if (in_array($origin, ALLOWED_ORIGINS, true)) {header("Access-Control-Allow-Origin: {$origin}");header('Vary: Origin');}if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { // preflight: answer and stopheader('Access-Control-Allow-Methods: GET, POST');header('Access-Control-Allow-Headers: Content-Type');header('Access-Control-Max-Age: 600');http_response_code(204);exit;}header('Content-Type: application/json');echo json_encode(['free' => ['09:30', '16:00']]), "\n";
Preflight requests: for requests that a plain HTML form couldn't make — methods like PUT or DELETE, a Content-Type: application/json body, custom headers — the browser first sends a preflight: an OPTIONS request asking whether the real request is allowed. The server answers 204 with Access-Control-Allow-Methods, Access-Control-Allow-Headers and optionally Access-Control-Max-Age (how long the browser may remember the answer). Only then is the real request sent. Your PHP code must answer OPTIONS without doing anything else. The diagram below shows the sequence.
A preflighted CORS request
JavaScript on www.tomsbarbershop.co.uk
fetch('https://bookbay.app/api/bookings', {method: 'POST', JSON body})
1. OPTIONS /api/bookings
Origin · Access-Control-Request-Method: POST · …-Headers: Content-Type
2. 204 No Content
Access-Control-Allow-Origin: https://www.tomsbarbershop.co.uk · Allow-Methods: GET, POST
3. The real POST
its response also carries Access-Control-Allow-Origin, so the script may read it
$ curl -i -X OPTIONS -H "Origin: https://www.tomsbarbershop.co.uk" -H "Access-Control-Request-Method: GET" "http://localhost:8000/misc.php?what=cors"HTTP/1.1 204 No ContentAccess-Control-Allow-Origin: https://www.tomsbarbershop.co.ukVary: OriginAccess-Control-Allow-Methods: GET, POSTAccess-Control-Allow-Headers: Content-TypeAccess-Control-Max-Age: 600$ curl -i -H "Origin: https://evil.example" "http://localhost:8000/misc.php?what=cors"HTTP/1.1 200 OK{"free":["09:30","16:00"]}# no Access-Control-Allow-Origin header: a browser won't let evil.example's JavaScript read this —# but curl (or any server) still gets the data. CORS is not access control.
CSRF: Cross-Site Request Forgery is the opposite problem: not reading, but sending. The browser attaches cookies — including the session cookie — to requests to BookBay even when the request was started by another site: a hidden form that submits itself, an image tag pointing at a URL. BookBay's server sees a valid session and does what's asked: Marcus's test cancelled a booking. The same-origin policy doesn't help, because the attacker doesn't need to read the response. Any action that changes data and relies on cookies to know who the user is — cancel, book, change password — is a target.
Defences: first, follow chapter 2: never change data with GET. Second, set session cookies with SameSite=Lax (chapter 6): the browser then doesn't send them with cross-site POSTs at all, which stops most CSRF. Third — the classic, complete defence — a CSRF token: a random secret stored in the visitor's session and placed in a hidden field of every form. On each POST, compare the submitted token with the session's using hash_equals(), and refuse with 403 if it's missing or wrong. Another site can make the browser submit a form, but it can't read your page to learn the token. The example shows it; Laravel adds @csrf to every form for exactly this. APIs that authenticate with a token in an Authorization header instead of cookies aren't exposed to CSRF, because browsers don't attach those headers automatically.
| CORS | CSRF | |
|---|---|---|
| Question | May another site's JavaScript READ my response? | Can another site make a visitor's browser SEND me a request? |
| Default | No: the browser blocks reading | Yes: the browser sends it, with cookies |
| Who enforces it | The browser | Your server |
| Your job | Allow specific origins with headers | Reject requests without a valid token |
| In PHP | header('Access-Control-Allow-Origin: …') | Session token + hidden field + hash_equals() |
CSRF, and how the token stops it
Barber logged in to bookbay.app
session cookie in the browser
Opens evil.example
a hidden form auto-POSTs to bookbay.app/cancel.php?id=4811
Without a token
the browser adds the session cookie → booking cancelled
With SameSite=Lax + CSRF token
no cookie on the cross-site POST, and no valid token → 403
<?phpsession_start();function csrfToken(): string{return $_SESSION['csrf'] ??= bin2hex(random_bytes(32)); // one random secret per session}// in the form:echo '<input type="hidden" name="csrf" value="', csrfToken(), '">', "\n";// on every POST, before doing anything:$sent = (string) ($_POST['csrf'] ?? '');if (!hash_equals(csrfToken(), $sent)) {http_response_code(403);exit("Your session expired. Please reload the form and try again.\n");}
$ curl -i -d "customer=Sam&date=2026-11-07&time=16:00" http://localhost:8001/book.phpHTTP/1.1 403 ForbiddenContent-type: text/html; charset=UTF-8Your session expired. Please reload the form and try again.
Key Takeaway
An origin is scheme + host + port. The browser's same-origin policy lets JavaScript send cross-origin requests but not read the responses; CORS headers (Access-Control-Allow-Origin from an allow-list, Vary: Origin) let chosen origins read them, and non-simple requests are preceded by an OPTIONS preflight answered with Allow-Methods/Allow-Headers. CORS protects visitors in browsers; it never locks your server. CSRF is another site making a logged-in visitor's browser send state-changing requests with its cookies; prevent it by never changing data on GET, using SameSite=Lax session cookies, and checking a per-session CSRF token in every form with hash_equals(). Token-authenticated APIs (Authorization header) aren't exposed to CSRF.
Why This Matters
CORS errors are the first wall every developer hits when a front end and an API live on different domains, and CSRF is on every security checklist. Knowing which is which saves hours of "just set Access-Control-Allow-Origin: *" fixes that open real holes.
Frameworks handle both — Laravel's CORS configuration and its @csrf tokens — but you choose the allowed origins and which routes need protection.
Tom's website can read the free slots, and every BookBay form carries a CSRF token. The booking pages themselves, though, are still echo statements full of HTML strings, and when a customer named <b>Sam</b> books, the barbers' schedule turns bold. That's the next chapter: rendering HTML with PHP templates.
