Security basics
Security isn't a separate skill bolted on at the end. It's the fundamentals applied with an attacker in mind: treat all input as untrusted, escape output, check who may do what, store passwords properly, keep secrets out of code, and keep dependencies updated. With real examples in PHP, Python, and JavaScript.
Several earlier parts ended with “part 22 comes back to this”. That’s because security isn’t a separate topic you learn at the end. Most security bugs are ordinary bugs: missing validation (part 13), strings pasted into SQL (part 19), a secret committed to Git (part 16), a cookie trusted too much (part 18), a race in a payment flow (part 21). The difference is that someone is actively looking for them.
This part pulls those threads together into a few habits that prevent most real-world problems.
The OWASP Top 10
A good map of what actually goes wrong is the OWASP Top 10, “a standard awareness document for developers and web application security.” The 2025 edition lists:
- Broken Access Control
- Security Misconfiguration
- Software Supply Chain Failures
- Cryptographic Failures
- Injection
- Insecure Design
- Authentication Failures
- Software or Data Integrity Failures
- Security Logging and Alerting Failures
- Mishandling of Exceptional Conditions
Notice how many of these map directly onto earlier parts of this series: error handling, logging, dependencies, design. The rest of this part covers the ones you’ll meet most often as a developer.
Rule 1: all input is untrusted
Everything that comes from outside your code can be anything: form fields, URL parameters, headers, cookies, uploaded files, JSON from an API, webhook bodies, even rows in your own database if users wrote them. The browser’s form validation and your JavaScript checks are conveniences for honest users; an attacker sends requests directly.
So validate at the edge, on the server, every time: types, lengths, ranges, allowed values (part 13). And when data crosses into another language (SQL, HTML, shell commands), it has to be handled for that language. That’s the next two rules.
Injection: keep data and code apart
Part 19 showed SQL injection: a search for x' OR '1'='1 turned into “return every customer” because the input became part of the SQL. The fix was placeholders, which send the value separately so it can never become code.
The same idea applies everywhere data meets a language:
- SQL: placeholders / prepared statements, always.
- Shell commands: avoid them; if you must, pass arguments as a list, never a single string built from input.
- HTML: escape on output (next section).
- File paths: never build them directly from input; a name like
../../.envwalks out of your upload folder.
XSS: escape on output
Cross-site scripting happens when user input ends up in a page as HTML instead of text. A product comment:
$comment = '<img src=x onerror="alert(document.cookie)">Nice book!';
echo "unsafe: <p>" . $comment . "</p>\n";
echo "escaped: <p>" . htmlspecialchars($comment) . "</p>\n";
unsafe: <p><img src=x onerror="alert(document.cookie)">Nice book!</p>
escaped: <p><img src=x onerror="alert(document.cookie)">Nice book!</p>
In the unsafe version, every visitor’s browser runs the attacker’s JavaScript, which can read cookies, act as the logged-in user, or change the page. In the escaped version it’s just text. PHP’s manual: “Certain characters have special significance in HTML, and should be represented by HTML entities if they are to preserve their meanings.” Python’s html.escape gives the same output.
OWASP’s guidance is to “use the appropriate context-specific output encoding”, and to “Prefer safe APIs that treat data as text.” Template engines (Blade, Twig, Jinja, React’s JSX) escape by default; the danger is the escape hatches: {!! !!}, |safe, dangerouslySetInnerHTML. In plain JavaScript, MDN warns that innerHTML “is probably the most common vector for cross-site scripting (XSS) attacks”, and: “Node.textContent should be used when you know that the user-provided content should be plain text.”
el.innerHTML = comment; // parses HTML: dangerous with user input
el.textContent = comment; // always plain text
Access control: check who, every time
Broken access control is number one on the list. “Access control enforces policy such that users cannot act outside of their intended permissions.” The most common form is the simplest: a URL like /orders/42, and the code fetches order 42 for whoever asks.
def get_order_unsafe(current_user, order_id):
return ORDERS[order_id]
def get_order(current_user, order_id):
order = ORDERS[order_id]
if order["owner"] != current_user:
raise Forbidden(f"user {current_user!r} may not view order {order_id}")
return order
unsafe, ana asks for 42: {'owner': 'budi', 'items': '10x pen', 'address': 'Jl. Sudirman 5, Jakarta'}
checked, ana asks for 42: user 'ana' may not view order 42
checked, ana asks for 41: 2x book
Ana is logged in, so authentication passed. But she can read Budi’s order and address just by changing the number in the URL. Authentication answers “who are you?”; authorization answers “may you do this?”. Both are needed, on every request, on the server. Hiding the button in the interface is not access control. Frameworks help (Laravel policies, Django permissions, middleware), but only if every route uses them; a single forgotten check is enough.
Passwords: hash slowly, never store them
You should never be able to tell a user their password. OWASP: “Passwords should never be stored in plain text.” Not encrypted either, because “Since encryption is a two-way function, attackers can retrieve the original plaintext from the encrypted data.” Store a hash, made with an algorithm designed to be slow: “Argon2id, bcrypt, or PBKDF2”. Fast hashes are the wrong tool: they “should be slow (unlike algorithms such as MD5 and SHA-1, which were designed to be fast)”.
The difference, on the machine used to write this note:
md5: 8,066,124 guesses/second
bcrypt: 18 guesses/second
If a database leaks, an attacker guessing passwords against MD5 hashes tries eight million per second per core. Against bcrypt, eighteen. That’s the whole point.
PHP makes the right thing easy. “password_hash() creates a new password hash using a strong one-way hashing algorithm”:
$hash = password_hash('correct horse battery staple', PASSWORD_DEFAULT);
// $2y$10$sPN7P9KJuZ2R5t0JPqx/VO5EQt8k7lwdKkw.SWOaWEySl/I3b/AJe
password_verify('correct horse battery staple', $hash); // true
password_verify('correct horse battery stapler', $hash); // false
Hashing the same password again gives a different hash, because a random salt is included, so two users with the same password don’t have the same hash. PASSWORD_DEFAULT is “designed to change over time as new and stronger algorithms are added to PHP”, so store hashes in a column that can grow beyond 60 characters. Python has hashlib.scrypt in the standard library and libraries like argon2-cffi; frameworks such as Django and Laravel do this for you. Never write your own.
Secrets and randomness
- Keep secrets out of code and out of Git. API keys, database passwords, webhook secrets go in environment variables or a secret manager. If one was ever committed, change it (part 16).
- Use cryptographic randomness for anything security-related: session IDs, reset tokens, API keys. Python’s docs: “secrets should be used in preference to the default pseudo-random number generator in the random module, which is designed for modelling and simulation, not security or cryptography.”
import secrets
secrets.token_urlsafe(32)
# 'bYfXYFrCDj6tccA0UhgBEv2GBpmCwR4mDyJW5VaJv9Y'
PHP’s equivalent is random_bytes() and random_int(); JavaScript has crypto.randomUUID() and crypto.getRandomValues().
Sessions, cookies, and CSRF
From part 18: a login is a cookie holding a random session ID. Protect it:
HttpOnlyso JavaScript (and therefore XSS) can’t read it.Secureso it’s only sent over HTTPS.SameSite=Lax(orStrict) so other sites can’t make the browser send it along with a forged request. That forged request is called CSRF; frameworks also add a per-form token to block it.- Regenerate the session ID on login and expire sessions after a while.
Errors, logs, and configuration
- Don’t show internals to users. Stack traces, SQL, file paths, and versions in error pages help attackers (part 13). Show a short message; log the details.
- Log security events: logins, failed logins, permission denials, password changes. Without logs, you can’t tell whether something happened.
- Never log secrets: passwords, full card numbers, tokens.
- Turn off debug mode in production. Framework debug pages (like
APP_DEBUG=truein Laravel) are built to show developers everything, which on a live site can include configuration and secrets.
Dependencies are code you didn’t write
Most of a modern application is libraries. “Software Supply Chain Failures” is number three on the 2025 list. Every package manager can check installed versions against known vulnerabilities:
$ npm audit --omit=dev
found 0 vulnerabilities
That’s this website’s own dependencies on the day this was written. composer audit does the same for PHP, pip-audit for Python, and govulncheck for Go. Run them regularly, update dependencies on a schedule, commit your lock file, and be suspicious of packages that are tiny, brand new, or have names one letter off from a popular one.
Thinking like an attacker
For each feature, ask a few questions:
- What input does this accept, and what’s the worst thing someone could send?
- Who should be allowed to do this, and where exactly is that checked?
- What happens if this request is sent twice, or a thousand times, or two at the same moment?
- If this table leaked tomorrow, what would be exposed?
You don’t need to be a security specialist to ask them. Most incidents come from a missing check that anyone on the team could have spotted.
Why this matters day to day
- Most breaches start with basics: a missing permission check, an unescaped field, a leaked key, an old library.
- Fixing later costs more. Adding placeholders, escaping, and access checks from the start is nearly free; retrofitting them after an incident isn’t.
- Trust is the product. Users don’t see your code, but they notice when their data leaks.
- AI-generated code regularly builds SQL with string formatting, uses
innerHTML, skips ownership checks, and hard-codes keys “for now”. Review it with this list.
Try it yourself
- Search a project for SQL built with string concatenation,
innerHTMLwith user data, and{!! !!}or|safein templates. - Pick one route that loads a record by ID. Where exactly does it check that the current user may see that record?
- Check how passwords are stored in a system you work on. If it’s anything other than a slow, salted hash, plan the migration.
- Run
npm audit,composer audit, orpip-auditon a project and read the results.
Summary
- Security is the fundamentals applied with an attacker in mind.
- All input is untrusted; validate on the server.
- Keep data and code apart: placeholders for SQL, escaping for HTML, no shell strings from input.
- Escape on output, prefer
textContentand template defaults over raw HTML. - Check authorization on every request: logged in is not the same as allowed.
- Hash passwords slowly (Argon2id, bcrypt) with the language’s built-in functions; never store or encrypt them.
- Secrets out of code, cryptographic randomness for tokens, secure cookie flags.
- Don’t leak internals, log security events, and audit dependencies regularly.
References
- OWASP Top 10 (2025 edition) and A01:2021 Broken Access Control.
- Password Storage Cheat Sheet and Cross Site Scripting Prevention Cheat Sheet, OWASP Cheat Sheet Series.
- password_hash and htmlspecialchars, PHP manual.
- Element: innerHTML, MDN Web Docs.
- secrets — Generate secure random numbers for managing secrets, Python documentation.