SitePoint Sponsor

User Tag List

Results 1 to 5 of 5
  1. #1
    SitePoint Enthusiast
    Join Date
    Nov 2008
    Posts
    73
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Casting to string before db query - secure?

    As the title suggests, I'm wondering if casting a slug to a string before attempting a mysql db lookup is a secure enough approach? Speaking to another developer about it and he thinks my ctype_alnum check isn't necessary, as a string cast would be sufficient! What do you guys suggest?

  2. #2
    From Italy with love silver trophybronze trophy
    guido2004's Avatar
    Join Date
    Sep 2004
    Posts
    9,501
    Mentioned
    163 Post(s)
    Tagged
    4 Thread(s)
    Are you using the mysql_ functions? Then you should pass the string through mysql_real_escape_string() before using it in a query.

    Have you considered passing on to PDO ?

  3. #3
    Non-Member
    Join Date
    Apr 2011
    Location
    no fixed address
    Posts
    851
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    what's in the slug and where has it come from - user input?

  4. #4
    SitePoint Enthusiast
    Join Date
    Nov 2008
    Posts
    73
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Each page on the site (CMS driven) will have a unique slug. I have a controller which will pass the slug in the request to a model, which will try to load a page from the db with the corresponding slug. I'm using an ORM which automatically escapes all values - on top of this I just wanted to check what else I should validate about the slug before trying the db query.

  5. #5
    SitePoint Wizard silver trophybronze trophy Cups's Avatar
    Join Date
    Oct 2006
    Location
    France, deep rural.
    Posts
    6,869
    Mentioned
    17 Post(s)
    Tagged
    1 Thread(s)
    If your ORM is escaping the values correctly then you should have nothing to worry about.

    If you have indexed the slug column correctly and you still feel the db is being put under undue duress because of repeated bad slug attempts then you could run the incoming slug against a regex.

    Something like:
    PHP Code:
    $str "128abc-"// letters numbers and a dash only > 4 chars and < 20 chars
    if( preg_match("#^[a-z0-9-]{4,20}$#i"$str) ) {
    // go ahead and do a lookup

    }else{
    // show some kind of default value



    You might well feel though that running a regex against every incoming slug would be slower than having to do the occasional wasteful db lookup - and you might well be right. Only you can tell whether this is worth bothering with.

    EDIT

    I should point out of course, that this check could be part of your .htaccess mod_rewrite rule ...


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •