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.
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.
// 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.
// 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.
XSS occurs when malicious JavaScript is injected into web pages and executed in users’ browsers.
// Outputting user input without escaping
<?php
echo "Hello, " . $_GET['name'];
?>
Using ?name=<script>alert('XSS')</script> executes JavaScript in the browser.
// Escaping user input before output
<?php
$name = htmlspecialchars($_GET['name'], ENT_QUOTES, 'UTF-8');
echo "Hello, $name";
?>
Special characters are escaped, preventing script execution.