Best way to escape strings for MySQL queries

Discussion in 'PHP' started by AHA7, May 26, 2007.

  1. #1
    Hello,

    Is the following the best way to prevent SQL injection?

    $site_URL = mysql_real_escape_string(stripslashes($URL));
    $query = mysql_query("INSERT INTO table site VALUES '$site_URL'");

    I want to store URLs which may have special chars such as %,&,*,/,\,...(I don't know if backslashes (\) are allowed in URLs but is it impossible to use them in legitimate URLs?).

    My question is how would the two functions stripslashes() and mysql_real_escape_string() affect my input URL ($URL) that contain some "special" characters?
     
    AHA7, May 26, 2007 IP
  2. wmtips

    wmtips Well-Known Member

    Messages:
    601
    Likes Received:
    70
    Best Answers:
    1
    Trophy Points:
    150
    #2
    Your code is ok. However, stripslashes is not necessary if you have magic_quotes_gpc disabled.
     
    wmtips, May 26, 2007 IP
  3. lemaitre

    lemaitre Peon

    Messages:
    61
    Likes Received:
    5
    Best Answers:
    0
    Trophy Points:
    0
    #3
    One solution is to disable magic_quotes_gpc in the php.ini file. If you want to write code that will work everywhere, you have to do something like this:

    if (get_magic_quotes_gpc()) {
      $URL = stripslashes ($URL);
    }
    $site_URL = mysql_real_escape_string($URL);
    $query = mysql_query("INSERT INTO table site VALUES '$site_URL'"); 
    PHP:
    Kind of a pain, but the PHP designers made some early mistakes and you have to learn to work around them.
     
    lemaitre, May 26, 2007 IP