0

This is sample code:

include("db_connect.php");
//
function foo($string){
    $s_array = array("'", '"');
    $result = str_replace($s_array, "\\", $string);
    return $result;
}
//
$first_var = $_POST['first_var'];
$second_var = intval($_POST['second_var']);
//
$first_var_result = foo($first_var);
//
mysql_query("UPDATE some_table SET first_column='".$first_var_result."', second_column='".$second_var."'  WHERE id='id'");

When $_POST['first_var'] equals ', foo function replaces ' with \ and mysql returns ERROR. This is not my code. I'm simpe interested in if this code is vulnerable (SQL Injection)? Thanks.

VusaL
  • 1
  • 1
  • 3
  • mysqli_escape_string use this method to avoid sql injection – Sailesh Kotha Feb 08 '15 at 16:06
  • Have a look [here](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php), so you can write safer code. – Jan Legner Feb 08 '15 at 16:13
  • Thank you for reply. But i dont want to avoid sql injection. This is not my code. I'm interested in, if this code is vulnerable. – VusaL Feb 08 '15 at 16:13
  • I'm web developer and i know how to avoid SQL injection with (mysql_real_escape_string, addslashes, htmlspecialchars or any custom functions). This is not what i want. – VusaL Feb 08 '15 at 16:19
  • “i know how to avoid SQL injection with (mysql_real_escape_string, addslashes, htmlspecialchars or any custom functions)” – No, apparently you don’t. Neither `addslashes`, nor `htmlspecialchars` and probably “any custom functions” either are appropriate for preventing SQL injections. You should be using parameterized statements as provided by prepared statements only! – Gumbo Feb 08 '15 at 17:24
  • I know about addslashes() vulnerability ("0xbf27 "). And as i said i know how to prevent SQL injection. And there are much more methods to prevent SQL injection with custom function(s). – VusaL Feb 08 '15 at 17:43

1 Answers1

0

Not this one but you are very close. If first_var_result ends with ' or ", the replacement \ will escape the apostrophe in the SQL query and second_var would be executed as code. If you would escape it with foo as well, you have SQL injection.

StenSoft
  • 9,369
  • 25
  • 30