-1

I want to sanitize data against mysql injection. So I need to write a pattern to recognize and remove 4 main mysql SELECT, Replace, DELETE , UPDATE.

I want to use this general rule for array_map

$_POST = array_map('stz',$_POST);

However I stuck in to write that pattern to against happens like this " ' AND 1=1; SELECT * FROM test_table "

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • 3
    What's wrong with using Prepared Statements? https://php.net/manual/de/mysqli.quickstart.prepared-statements.php – BenM Jan 06 '14 at 12:53
  • what's supposed to be in the $_POST ? – David Lin Jan 06 '14 at 12:54
  • 1
    Or if you're using an API without prepared statements, what's wrong with its escape function? – Barmar Jan 06 '14 at 12:55
  • 3
    This is absolutely the wrong approach. Consult [this SO question/answer](http://stackoverflow.com/questions/129677/whats-the-best-method-for-sanitizing-user-input-with-php?rq=1) and [this reddit discussion](http://www.reddit.com/r/PHP/comments/1u9jl5/how_do_you_handle_sanitizing_get_and_post/). – DCoder Jan 06 '14 at 12:56
  • Why inventing the wheel? use $stz = mysql_real_escape($_POST['stz']); – talsibony Jan 06 '14 at 13:04
  • @talsibony the proper function is `mysqli_escape_string()` – rybo111 Jan 06 '14 at 13:09
  • @rybo111 You are right (depricated in newer versions of PHP) – talsibony Jan 06 '14 at 13:13

2 Answers2

1

There are a number of ways you can do it. Here are a few:

Create a variable each time

$clean_forename = mysqli_escape_string($db, $_POST["forename"]);

Create a clean array

$clean = array();
$clean["forename"] = mysqli_escape_string($db, $_POST["forename"]);

Sanitize in the SQL query

$sql_query = "UPDATE table SET forename='".mysqli_escape_string($db, $_POST["forename"])."'";

Use a foreach

$set = array();
$keys = array('forename', 'surname', 'email');
foreach($keys as $val) {
  $safe_value = mysqli_escape_string($db, $_POST[$val]);
  array_push($set, "$val='$safe_value'");
}
$set_query = implode(',', $set);
$sql_query = "UPDATE table SET $set_query";
rybo111
  • 12,240
  • 4
  • 61
  • 70
-3

Don't use regex. there is dedicated function for cleaning if you wish to clean all your post array you can use simple foreach:

<?php
    $cleanpostArr = array();
    foreach($_POST as $postkey => $postvalue){
      $cleanpostArr[mysqli_escape_string($db,$postkey)] = mysqli_escape_string($db,$postvalue);
    }
?>
talsibony
  • 8,448
  • 6
  • 47
  • 46