← Back to Chapters

Preventing SQL Injection & XSS

?️ Preventing SQL Injection & XSS

? Quick Overview

SQL Injection and Cross-Site Scripting (XSS) are among the most critical web security vulnerabilities. They allow attackers to manipulate SQL queries or inject malicious JavaScript, potentially exposing databases and compromising user data.

? Key Concepts

  • SQL Injection manipulates database queries
  • XSS injects executable JavaScript into webpages
  • User input must never be trusted
  • Prepared statements and output escaping are essential

? Syntax & Theory

Both SQL Injection and XSS occur due to improper handling of user input. SQL Injection targets the database layer, while XSS targets the browser execution context.

? SQL Injection Example (Unsafe)

? View Code Example
// Unsafe SQL query with direct user input
<?php
$username = $_POST['username'];
$password = $_POST['password'];
$query = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$result = mysqli_query($conn, $query);
?>

If a user enters ' OR '1'='1 as the username, authentication is bypassed.

? Preventing SQL Injection

? View Code Example
// Secure query using prepared statements
<?php
$stmt = $conn->prepare("SELECT * FROM users WHERE username=? AND password=?");
$stmt->bind_param("ss", $username, $password);
$stmt->execute();
$result = $stmt->get_result();
?>

Prepared statements ensure input is treated strictly as data.

⚡ What is XSS?

XSS occurs when malicious JavaScript is injected into web pages and executed in users’ browsers.

? XSS Example (Unsafe)

? View Code Example
// Outputting user input without escaping
<?php
echo "Hello, " . $_GET['name'];
?>

Using ?name=<script>alert('XSS')</script> executes JavaScript in the browser.

?️ Preventing XSS

? View Code Example
// Escaping user input before output
<?php
$name = htmlspecialchars($_GET['name'], ENT_QUOTES, 'UTF-8');
echo "Hello, $name";
?>

Special characters are escaped, preventing script execution.

? Use Cases

  • Login systems
  • Search forms
  • Comment sections
  • Contact forms

✅ Tips & Best Practices

  • Always use prepared statements for SQL
  • Escape all output displayed in HTML
  • Validate and sanitize user input

? Try It Yourself

  • Create an unsafe login form and exploit it
  • Secure it using prepared statements
  • Build a comment system and protect it from XSS