---
title: "3. mitigating sqli"
date: 2024-09-28
draft: false
---

example
```php
<SNIP>
  $username = $_POST['username'];
  $password = $_POST['password'];

  $query = "SELECT * FROM logins WHERE username='". $username. "' AND password = '" . $password . "';" ;
  echo "Executing query: " . $query . "<br /><br />";

  if (!mysqli_query($conn ,$query))
  {
          die('Error: ' . mysqli_error($conn));
  }

  $result = mysqli_query($conn, $query);
  $row = mysqli_fetch_array($result);
<SNIP>
```

`username` and `password` taken from post request and passed to query directly letting attackers inject anything they want into the application 
injection can be avoided with sanitization 
libs provide functions to do this 

https://www.php.net/manual/en/mysqli.real-escape-string.php

this function escapes chars like `'` and `"` so they dont hold any special meaning 

```php
<SNIP>
$username = mysqli_real_escape_string($conn, $_POST['username']);
$password = mysqli_real_escape_string($conn, $_POST['password']);

$query = "SELECT * FROM logins WHERE username='". $username. "' AND password = '" . $password . "';" ;
echo "Executing query: " . $query . "<br /><br />";
<SNIP>
```
thus we can no longer escape single quotes
similar example is pg_escape_string in postgresql 
https://www.php.net/manual/en/function.pg-escape-string.php

user input can also be validated based on data used
when taking email validate input is in form of `@email.com` for example 

in our ports example we can use regex 
```php
<SNIP>
$pattern = "/^[A-Za-z\s]+$/";
$code = $_GET["port_code"];

if(!preg_match($pattern, $code)) {
  die("</table></div><p style='font-size: 15px;'>Invalid input! Please try again.</p>");
}

$q = "Select * from ports where port_code ilike '%" . $code . "%'";
<SNIP>
```

this regular expression allows only letters and characters 
code modified to use `preg_match()` func which checks if input matches given pattern or not 


## user privs to avoid sqli 
refer to previous section and reverse them
dbs should not be run by server user with administrative privileges 
the user themselves used to execute queries should only ever be `READ` permission users


## parameterized queries to avoid sqli 

```php
<SNIP>
  $username = $_POST['username'];
  $password = $_POST['password'];

  $query = "SELECT * FROM logins WHERE username=? AND password = ?" ;
  $stmt = mysqli_prepare($conn, $query);
  mysqli_stmt_bind_param($stmt, 'ss', $username, $password);
  mysqli_stmt_execute($stmt);
  $result = mysqli_stmt_get_result($stmt);

  $row = mysqli_fetch_array($result);
  mysqli_stmt_close($stmt);
<SNIP>
```

