简体   繁体   中英

Secure a dynamic where clause (PDO)

In my form I have a select and an input, like this:

<div class="row">
  <div class="col-md-4">
    <select id="select-column" name="column" class="form-control">
      <option value="bin_id">Bin ID</option>
      <option value="table_col_one">Column One</option>
      <option value="table_col_two">Column Two</option>
      <option value="table_col_three">Column Three</option>
    </select>
  </div>

  <div class="col-md-8">
    <div>
      <input id="search" name="term" type="text" class="form-control">
    </div>
  </div>
</div>

The user selects a column in which to search, here is my SQL query:

$term = $_POST['term'];
$column = $_POST['column'];

$sql = "SELECT $column FROM packing_master WHERE $column LIKE :term AND invoice != '' group by $column LIMIT 35";
$stmt = $bdd->prepare($sql);
$stmt->bindParam(':term', $term);
$stmt->execute();

But how to secure the request? Because it is vulnerable to sql injection?

Use white list with allowed columns names:

$term = $_POST['term'];
$column = $_POST['column'];

$allowed_columns = ['col1', 'col2', 'col3']; 
// or query a database to get columns in the table you're operating on

if (!in_array($column, $allowed_columns)) {
    // throw exception or do anything else that prevents further query execution
}

Well, basically the parameter binding is essential for protecting your web application from SQL-injection. Pretty much all data which is going to be used in SQL statement needs binding. Binding simply saying is just a way to tell engine that a particular piece of data is a string, number, character and so on. By doing this special characters like quotes and double quotes, semi-colons, etc. won't be interpreted as commands by the database.

Example:

public function dbSelect($table, $fieldname=null, $id=null) {
    $this->conn();
    $sql = "SELECT * FROM `$table` WHERE `$fieldname`=:id";
    $stmt = $this->db->prepare($sql);
    $stmt->bindParam(':id', $id);
    $stmt->execute();

    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM