-2

i want to secure my sql queries without pdo or prepare statement
can this function do ?

function sql_escape($string)
{
    $string =   iconv(mb_detect_encoding($string),'UTF-8//IGNORE',$string);
    $string =   addslashes($string);
    $string =   preg_replace('/[\x00-\x1F\x80-\xFF\0xB4\0x60\0x96\0x97\0x95\0x94\0x93\0x92\0x91\0x84\0x82\0x3B\0x8A]/', '', $string);
    $string =   addslashes($string);
    return $string;
}
Andy Lester
  • 91,102
  • 13
  • 100
  • 152
  • It's not just a matter of security, but of deprecated functions as well. They made [new] good things for you, use them : )) – moonwave99 Jul 02 '13 at 17:20
  • `\x80- ` (space, 0x20) is an invalid range. – Gumbo Jul 02 '13 at 17:20
  • @Gumbo the space came while pasting the code :) – Mohammed Al Ashaal Jul 02 '13 at 17:23
  • Don't trust REGEX for data validation. – Rob W Jul 02 '13 at 17:23
  • @RobW Could U tell me Why ? :) – Mohammed Al Ashaal Jul 02 '13 at 17:25
  • If you have to use REGEX to even attempt to do data validation (in most scenarios), then you're doing it wrong. `Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems.` - Jamie Zawinski – Rob W Jul 02 '13 at 17:30
  • And by data validation, I mean "validating the data is OK for the database"-validation. – Rob W Jul 02 '13 at 17:32
  • All you need to do is escape any character the database will interpret as a string terminator or otherwise special character. Everything else is just pointless song and dance with which you're destroying the original value little by little. [The Great Escapism (Or: What You Need To Know To Work With Text Within Text)](http://kunststube.net/escapism/) – deceze Jul 02 '13 at 20:15

2 Answers2

4

No, use the supplied escape function. For mysqli this is mysqli_real_escape_string.

Don't reinvent the wheel, especially if it's a very complex wheel and you're not really sure it works in all conditions.

Halcyon
  • 57,230
  • 10
  • 89
  • 128
-1

Like many PHP folks you are confusing escaping with protection from injection. So, someday your site will be hacked and you'll come here ready to learn something useful at last.

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345