Cybersecurity Tutorial menu

Web Security Basics: XSS and SQL Injection

Websites take input from users: search boxes, login forms, comments. If a website trusts that input too much, attackers can abuse it.

The Golden Rule

Never trust user input. Everything a visitor types, uploads or sends should be checked and handled safely. Two of the most common mistakes that break this rule are SQL injection and cross-site scripting (XSS).

This chapter explains them so you can prevent them. Only test security on websites you own or have written permission to test.

SQL Injection

Many websites store data in a database and use SQL to read it. The problem starts when a developer builds the SQL query by gluing user input into the query text.

The unsafe way

Imagine a login check written like this in Python:

Example

python
username = input("Username: ")
query = "SELECT * FROM users WHERE username = '" + username + "'"
print(query)

If a normal user types ayesha, the query is fine:

Output
SELECT * FROM users WHERE username = 'ayesha'

But the input becomes part of the code. If someone types a quote mark and some extra SQL, they can change what the query means, for example making a condition always true, and the database may return every user. That is SQL injection: user input is treated as instructions instead of plain data.

The safe way: parameterised queries

The fix is to send the query and the data separately. The database then always treats the input as a value, never as code:

Example

python
import sqlite3

conn = sqlite3.connect(":memory:")
conn.execute("CREATE TABLE users (username TEXT, city TEXT)")
conn.execute("INSERT INTO users VALUES ('ayesha', 'Karachi')")

username = input("Username: ")
rows = conn.execute(
    "SELECT username, city FROM users WHERE username = ?", (username,)
).fetchall()
print(rows)
Output
Username: ayesha
[('ayesha', 'Karachi')]

The ? is a placeholder. Whatever the user types, even quote marks, is only compared as text. The same idea exists in every language: prepared statements in PHP (PDO), Java, Node.js and others.

More protections:

  • Give the website's database user only the permissions it needs
  • Use an ORM or query builder that uses parameters for you
  • Show general error messages, not database errors, to visitors

Cross-Site Scripting (XSS)

XSS happens when a website shows user input on a page without escaping it, and the browser runs it as code.

Imagine a comment box on a shop website. If someone writes a comment containing an HTML <script> tag, and the site prints the comment as raw HTML, then every visitor's browser runs that script. It could steal their session and log in as them.

The fix: escape output

Escaping turns special characters into harmless text. For example < becomes &lt;, so the browser shows the character instead of starting a tag:

Example

python
import html

comment = '<b>Great shop!</b> <script>alert("hi")</script>'
print(html.escape(comment))
Output
&lt;b&gt;Great shop!&lt;/b&gt; &lt;script&gt;alert(&quot;hi&quot;)&lt;/script&gt;

The visitor now sees the comment as plain text, and no script runs.

In JavaScript, put user text in the page with textContent, not innerHTML:

Example

javascript
const comment = document.getElementById("comment");
comment.textContent = userInput;   // safe: shown as text
// comment.innerHTML = userInput;  // unsafe: may run as HTML

Modern frameworks such as React, Vue and Angular escape output by default, which removes most XSS risk, as long as you do not bypass that protection.

More protections:

  • A Content Security Policy (CSP) header tells the browser which scripts are allowed
  • Mark session cookies as HttpOnly so scripts cannot read them
  • Validate input: if a field is a phone number, accept only digits

Summary

WeaknessCauseMain prevention
SQL injectionUser input mixed into SQL codeParameterised queries
XSSUser input shown as raw HTMLEscape output, use textContent, CSP

Other common weaknesses to read about next are broken access control, weak session handling and outdated plugins. The OWASP Top 10 is a well-known list of the most serious web risks.

Exercise

Exercise

What is the best way to prevent SQL injection?

Learn Cybersecurity with a teacher

Join the CIT (Computer Information Technology) course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp