Skip to content
Tutorials Center
My learning

Topics

Lesson 95 of 147 ยท Security

Web Security Basics

Learn how PHP web apps get attacked and how to think about defense - common threats, trust boundaries, never trusting input, allowlists and defense in depth.

The moment your PHP code is on a public server, strangers can send it anything. Most visitors are people using your site normally, but a steady stream of requests comes from bots that try known attacks on every site they find, around the clock. Security isn't a feature you add at the end; it's a way of writing every function that touches a request, a database, a file or another person's data.

This lesson gives you the mental model the rest of the Security chapter builds on: what attackers typically try, where the trust boundaries in a PHP application are, why "never trust input" means more than it sounds, and how defense in depth keeps one mistake from becoming a breach. The following lessons then cover the big threats one by one: XSS, CSRF, password storage, cryptography and a secure coding checklist.

What attackers try

The OWASP Top 10, maintained by the Open Worldwide Application Security Project and updated every few years, is the best-known list of web application risks. The exact ranking changes between editions, but the same families appear every time. Here they are with what they look like in PHP:

Threat What it looks like in PHP Where to learn the defense
Broken access control invoice.php?id=42 shows any user's invoice if you change the number This lesson, Sessions
Injection User input concatenated into SQL, shell commands or file paths Prepared Statements, Secure Coding
Cross-site scripting (XSS) A comment containing <script> is echoed without escaping Preventing XSS
Cross-site request forgery (CSRF) Another site makes the victim's browser submit your "delete account" form Preventing CSRF
Authentication failures Passwords stored with md5(), no limit on login attempts, session IDs that never change Password Hashing, Sessions
Cryptographic failures Home-made encryption, predictable tokens from rand() Cryptography
Security misconfiguration display_errors=On in production, .env or .git folders reachable over HTTP Errors, Deploying
Vulnerable components Old PHP versions or Composer packages with known holes Autoloading and Composer
Insecure deserialization unserialize() on a cookie value Comparing, Copying and Serializing Objects
Server-side request forgery (SSRF) Your server fetches any URL a user submits, including internal ones Secure Coding
Missing logging Nobody notices 10,000 failed logins in an hour Errors

You don't need to memorize the list. You need to recognize the underlying pattern: almost every item is either data treated as code (injection, XSS, deserialization) or a request the server should have refused (access control, CSRF, authentication).

Trust boundaries

A trust boundary is any point where data crosses from a place you don't control into one you do. Draw the boundaries of a typical PHP application and you get:

  • The HTTP request: URL, query string, form fields, cookies, headers, uploaded files, the raw body. All of it comes from the client, and the client can be a script, not a browser.
  • The database: data you stored earlier may have come from a user, and a different part of the system may have stored it without validating.
  • Files and uploads: names, contents and metadata are all chosen by whoever uploaded them.
  • Other services: API responses, webhooks, message queues, even DNS.
  • The environment: configuration and environment variables, which are trusted only because you set them.

Inside the boundary, your code can rely on values being the type and shape it expects, because they were checked at the boundary. The goal is to check once, at the edge, and then work with clean, typed data.

The client is not your code

Beginners often trust things that "the user can't change": a hidden form field, a <select> list, a disabled button, a price in a data attribute, or the JavaScript that validates a form. In reality, every byte of a request can be crafted with curl or the browser's developer tools. This simulated checkout shows the classic mistake of trusting a price sent by the browser:

PHP Trusting a hidden price field

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The unsafe version charges 2 cents for two posters; the safe one charges 5000. A negative quantity, which would have produced a refund, is rejected. Client-side validation is still worth having, but only as a convenience for honest users. The server must check everything again.

The same goes for request headers. $_SERVER['HTTP_HOST'], $_SERVER['HTTP_REFERER'], $_SERVER['HTTP_USER_AGENT'] and $_SERVER['HTTP_X_FORWARDED_FOR'] are copied straight from what the client sent. Building password-reset links from HTTP_HOST has caused real account takeovers: the attacker sends a reset request with Host: evil.example, and the victim's email contains a link to the attacker's site. Use a configured base URL instead.

Never trust input: validate, then encode

"Never trust input" has two halves, and you need both:

  1. Validate on the way in. Check that the value has the type, length, format and range your code expects, and reject it if not. A product ID is a positive integer; an email address passes FILTER_VALIDATE_EMAIL; a sort direction is asc or desc.
  2. Encode on the way out. When a value goes into another language (HTML, SQL, a shell command, a URL, JSON), use the tool built for that context: htmlspecialchars(), prepared statements, escapeshellarg(), rawurlencode(), json_encode(). Validation alone isn't enough, because a perfectly valid name like O'Brien still breaks naively built SQL.

Allowlists beat blocklists

A blocklist tries to remove the bad things. An allowlist describes the good things and rejects everything else. Blocklists fail because attackers are more creative than any list. Here's a "sanitizer" that strips <script> tags, and three inputs that walk straight past it:

PHP Why blocklists fail

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

All three attacks survive the blocklist with working JavaScript. The allowlist regex, by contrast, says exactly what a username may contain, so there's nothing to bypass. For free text like comments, where an allowlist isn't possible, you don't filter at all: you store the text as written and escape it on output, which the XSS lesson covers.

Broken access control

The number one risk in recent OWASP lists isn't a clever injection. It's code that simply forgets to check whether the current user is allowed to do what they asked. The most common form is the insecure direct object reference (IDOR): an ID in the URL that anyone can change.

PHP Checking ownership, not just login

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Note that the query is a prepared statement, so it's immune to SQL injection, and it's still a serious hole. Being logged in answers "who are you?"; access control answers "may you do this?". Check it on the server for every request that reads or changes a resource, including API endpoints and AJAX handlers that "only our JavaScript calls". Answering with 404 rather than 403 also avoids confirming which IDs exist.

Defense in depth

No single defense is perfect, so secure systems stack several independent ones. If one layer fails, the next one limits the damage. For a typical PHP application, the layers look like this:

  • Input validation rejects malformed data at the boundary.
  • Prepared statements stop SQL injection even if validation misses something.
  • Output escaping stops XSS even if a malicious string got stored.
  • A Content-Security-Policy header blocks injected scripts even if escaping was forgotten once.
  • Least privilege: the database user can't DROP TABLE, PHP can't write to its own code folders, and services listen only on private networks.
  • Logging and monitoring notice the attack that got through.

One of the cheapest layers is error handling. A detailed error message is gold for an attacker: it can reveal file paths, SQL queries, library versions and sometimes passwords in a DSN. In production, set display_errors=Off and log_errors=On, and show visitors a generic page. A top-level exception handler does both:

PHP Generic errors for users, details in the log

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The visitor sees a short apology and a random reference code they can quote to support, while the log keeps the exception class, the message (which names the table the code tried to read) and the file and line. The reference code lets you find the matching log entry. The Custom Exceptions lesson covers handlers in more detail.

A security mindset

Most vulnerabilities aren't exotic. They come from a handful of habits being skipped once. Keep these questions in mind whenever you write code that touches a request:

  • Where did this value come from? If the answer involves a user, a file or another system, it's untrusted until checked.
  • Where is it going? HTML, SQL, a shell, a file path or a URL each need their own encoding.
  • Who is allowed to do this? Check authorization on the server, per resource, every time.
  • What happens when it fails? Fail closed (deny), log the details, and show a generic message.
  • What if this layer is bypassed? Make sure another one still stands.

Finally, keep things up to date. Each PHP version gets security fixes for a limited time (two years of active support plus two of security fixes for current releases), and Composer packages publish fixes for known holes. Running composer audit regularly lists dependencies with published advisories.

Use the well-tested tools PHP already gives you instead of writing your own: password_hash() for passwords, random_bytes() for tokens, prepared statements for SQL, htmlspecialchars() for HTML, and a framework's built-in CSRF and session handling where you can. Security code is the worst place for originality.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A checkout form sends the price in a hidden field. What should the server do with it?

    Every part of a request can be changed by the client. The client may choose what to buy; the server must decide what it costs.
  2. 2. A sanitizer removes every "<script>" substring from comments. Why is that not enough?

    Blocklists miss variations. Validate structured input with allowlists, and escape free text on output.
  3. 3. Logged-in user 1 requests /invoice.php?id=2 and sees user 2's invoice. The query uses a prepared statement. What is the vulnerability?

    The code checks who the user is but not whether they own the invoice. Add the owner to the query - WHERE id = ? AND user_id = ?.
  4. 4. Which value in $_SERVER can you trust without checking?

    Every HTTP_* entry is copied from a request header, which the client controls completely.
  5. 5. What does defense in depth mean?

    Validation, prepared statements, output escaping, CSP, least privilege and logging each cover for the others' gaps.

Summary

  • Attacks fall into a few families; most are data treated as code (injection, XSS) or requests the server should have refused (access control, CSRF, weak authentication).
  • A trust boundary is where outside data enters your code: the request, the database, files, other services. Check data at the boundary, then work with clean, typed values.
  • Everything in a request is attacker-controlled: hidden fields, select options, cookies and every HTTP_* header. The server decides prices, permissions and URLs.
  • Validate input with allowlists and encode output for its context. Blocklists get bypassed.
  • Access control must be checked on the server for every resource: being logged in isn't the same as being allowed.
  • Defense in depth stacks layers: validation, prepared statements, escaping, CSP, least privilege, generic error pages with detailed logs, and up-to-date dependencies.

Next: Preventing XSS