sql injection

Discussion in 'PHP' started by promotingspace.net, Apr 24, 2010.

  1. #1
    Hi
    I usually use mysql_real_escape_string($_POST['field']) to avoid sql injection
    But this time The form inputs contains single quotes and when I use mysql_real_escape_string it adds a lot of \\\ to the input. It causes problems. In addition I noticed $_POST adds a \ before single quotes, maybe I don't need mysql_real_escape_string anymore?

    Any idea?
    Thanks in advance
     
    promotingspace.net, Apr 24, 2010 IP
  2. danx10

    danx10 Peon

    Messages:
    1,179
    Likes Received:
    44
    Best Answers:
    2
    Trophy Points:
    0
    #2
    Its probably because magic quotes is enabled, instead of using mysql_real_escape_string() use the following function; clean().

    <?php
    function clean($input) {
    $input = trim($input);
    $input = get_magic_quotes_gpc() ? stripslashes($input) : $input;
    if (!is_numeric($input)){
    //prevent sql injection...
    $input = mysql_real_escape_string($input);
    }
    return $input;
    }
    
    //example usage
    $field  = clean($_POST['field']);
    ?>
    PHP:
    or if you have php.ini access set magic_quotes_gpc to Off, so php.ini should look like (or contain):

    magic_quotes_gpc = Off
    Code (markup):
     
    danx10, Apr 24, 2010 IP
  3. krsix

    krsix Peon

    Messages:
    435
    Likes Received:
    11
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Use PDO/prepared statements for SQL. Don't directly query.
     
    krsix, Apr 24, 2010 IP
  4. s.ham

    s.ham Member

    Messages:
    35
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    41
    #4
    Use intval function for numeric inputs before you apply in query.
     
    s.ham, May 2, 2010 IP
  5. krsix

    krsix Peon

    Messages:
    435
    Likes Received:
    11
    Best Answers:
    0
    Trophy Points:
    0
    #5
    Do not query at all. Use prepared statements.
     
    krsix, May 3, 2010 IP