I'm trying to understand how SQL injections fully work in order to feed this information back to some of my students. I have created a simple webpage with a small SQL database attached and would like my students to attempt to "break into" the site and get the token on the welcome page.
However, the resource I used (w3schools) to create the login page only showed me a secure webpage, and I'm not sure how to unravel it to make the login page susceptible to an SQL injection.
So far, the code I have for the webpage is below (stripped to only the essential part of the HTML!)
<?php
include("conf.php");
session_start();
if($_SERVER["REQUEST_METHOD"] == "POST") {
$myusername = mysqli_real_escape_string($db,$_POST['username']); //get username and password from form
$mypassword = mysqli_real_escape_string($db,$_POST['password']);
$sql = "SELECT * FROM admin WHERE username = '$myusername' and password = '$mypassword'"; //sql query - IF username AND password match what is in the database
$result = mysqli_query($db,$sql);
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
$active = $row['active'];
$count = mysqli_num_rows($result); //return the number of results - there should only be one!
if($count == 1) { //if there was 1 result, load the welcome page
$_SESSION['username'] = $myusername;
header("location: welcome.php");
}else { //otherwise show an error
$error = "Your Login Name or Password is invalid";
}
}
?>
<html>
<center>
<form action = "" method = "post">
<label>UserName :</label><input type = "text" name = "username" class = "box"/><br /><br />
<label>Password :</label><input type = "password" name = "password" class = "box" /><br/><br />
<input type = "submit" value = " Submit "/><br />
</form>
</center>
</body>
</html>
I've attempted to change the line:
$myusername = mysqli_real_escape_string($db,$_POST['username']);
to
$myusername = $_POST['username'];
as I assumed that it was being escaped (mysqli_real_escape_string) and preventing any extra characters from being entered into the text box - is that correct?
But that didn't do anything. Any help would be appreciated.