SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Evangelist
    Join Date
    May 2006
    Posts
    436
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)

    What's your procedure for validating/sanitising data

    I tend to find you can sanitise/validate data as it comes in from GET, POST, etc. I never deal directly with $_GET or $_POST; I have to get it via a cleaner object and tell it what data type I'm expecting. Anything more specific than that (e.g. it needs to be a four digit int greater than 2000 and less then 3000) is done is more specific classes/functions.

    It occurred to me though, should you write functions as though the scalar type has already been checked?

    You could have:

    PHP Code:
    function foo($int) {
        
    $int = (int) $int;
        
    // Do something

    Or:

    PHP Code:
    function foo($int) {
        
    // Assume it's an int
        // Do something

    The first is leaner on code but, in theory, another programmer could pass an array to foo(); In this case, PHP would just issue a warning. If you check data types, etc on every function I'm thinking code will end up too bloated.

    Is validating/sanitising twice "just to be on the safe side" bad practice? What is your procedure/policy?

  2. #2
    SitePoint Wizard bronze trophy Jeff Mott's Avatar
    Join Date
    Jul 2009
    Posts
    1,264
    Mentioned
    18 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by DrQuincy View Post
    I tend to find you can sanitise/validate data as it comes in from GET, POST, etc. I never deal directly with $_GET or $_POST; I have to get it via a cleaner object and tell it what data type I'm expecting. Anything more specific than that (e.g. it needs to be a four digit int greater than 2000 and less then 3000) is done is more specific classes/functions.

    ...

    Is validating/sanitising twice "just to be on the safe side" bad practice? What is your procedure/policy?
    I'd think it's less good to validate twice, because it means code that logically belongs together is actually split. You can't just look at your validation classes/functions and know if you've checked everything that needs to be checked, because you're relying on some of those checks being done elsewhere. I'd think that the responsibilities of your cleaner object should be moved into the validation classes/functions. That is, your validation might check that it's an int and that it's four digits between 2000 and 3000. And with that logic consolidated, there's no longer any need to re-check the data type elsewhere.
    "First make it work. Then make it better."


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
  •