SQL injection, XSS and CSRF: mechanism and defence
In SQL injection input becomes SQL code, in XSS a foreign script runs in the victim's browser, and CSRF makes that browser send a request with its cookie. Defences: parameterised queries, context-aware output encoding with CSP, an anti-CSRF token and SameSite on the session cookie. Keyword blacklists and manual escaping are unreliable.
A site search builds a query by string: "... WHERE name = '" + term + "'". A user enters ' OR 1=1-- and gets the whole catalogue. These are three classic web attacks that are often confused.
SQL injection. Input becomes part of the SQL command. Kinds: error-based (the database error is visible), UNION-based (the result of another query is appended), blind (the response gives only yes/no or a timing difference). Defence: parameterized queries (prepared statements), least-privilege database accounts. Keyword blacklists and manual quote escaping are unreliable.
XSS — someone else's script runs in the victim's browser. Reflected — a request value goes straight into the response; stored — it is saved (a comment) and runs for everyone who opens the page; DOM-based — the unsafe insertion happens in client JS (innerHTML). Defence: output encoding by context (HTML, attribute, JS), safe APIs (textContent), and additionally CSP (Content-Security-Policy), which limits script sources. HttpOnly does not prevent XSS, it only stops a script from reading the cookie.
CSRF — an attacker's page makes a logged-in user's browser send a request to your site, and the browser adds the cookie itself. Defence: an anti-CSRF token, SameSite=Lax or Strict for the session cookie, an Origin check. The fact that a request "contains the session cookie" proves nothing: CSRF relies on exactly that.
CSRF test example. Send an email change without a token from a third-party page in a test environment: if it changed, there is no protection.
Mistakes: "protecting" with validation in the browser only; thinking POST instead of GET stops CSRF; mixing up XSS (foreign code in your site) and CSRF (a foreign request from your user).
Short answer: "SQLi — parameterization; XSS — output encoding and CSP; CSRF — tokens and SameSite".