SitePoint Sponsor

User Tag List

Page 1 of 2 12 LastLast
Results 1 to 25 of 39
  1. #1
    SitePoint Wizard
    Join Date
    Oct 2001
    Location
    Tucson, Arizona
    Posts
    1,858
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Data Sanitization

    It seems like the subject of data sanitization is hardly ever talked about in regards to PHP apps. This is troubling to me, since the majority of PHP projects are Web-oriented. And as we all know, the Web is a very dangerous place.

    Having said that, what methods do you use to sanitize and disinfect user input? Do you use something as simple as the function below, or do you favor a full-blown set of classes--or something else?

    PHP Code:
    function clean($string$length 255)
    {
        
    $cleaned trim($string);
        
    $cleaned strip_tags($cleaned);
        
    $cleaned substr($cleaned0$length);
        
    $cleaned addslashes($cleaned);

        return 
    $cleaned;


  2. #2
    Non-Member
    Join Date
    Jan 2004
    Location
    Planet Earth
    Posts
    1,764
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    For me at the moment, just clean up the data prior to database insertion, though I would really like to seperate this from the Model

    Have yet to see a really decent class to do what you ask though

  3. #3
    SitePoint Addict pachanga's Avatar
    Join Date
    Mar 2004
    Location
    Russia, Penza
    Posts
    265
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    We're thinking of using special variable prefixes and cleaning super global $_REQUEST in the very begining.
    (i.e
    1) int_*, id_* should be converted into integer
    2) date_* should be transformed into stamp
    etc etc)

    I think it's convinient:
    <input type='hidden' name='id_node'>

  4. #4
    ********* Wizard silver trophy Cam's Avatar
    Join Date
    Aug 2002
    Location
    Burpengary, Australia
    Posts
    4,495
    Mentioned
    0 Post(s)
    Tagged
    1 Thread(s)
    I use something along these lines, usually just coded inline, not as a specific function.
    PHP Code:
     $string addslashes(htmlspecialchars(trim($source))); 
    Occasionally no htmlspecialchars() and some regex to remove unwanted HTML such as <script> and the like.

  5. #5
    SitePoint Zealot
    Join Date
    Jun 2003
    Location
    Elsewhere
    Posts
    107
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I use a single object that serves as sole distributor for all incoming parameters, and which runs them all through a couple of filters before they can be used by other application objects:
    • trim()
    • & -> [amp]
    • < -> [lt]
    • > -> [gt]
    • " -> [quot]
    • newline -> [br]


    This way, user input is safe to use everywhere in my application, and none of my business objects need direct access to $_GET, $_POST, $_COOKIE, etcetera. It's also quite easy to transform these BB tags into either safe HTML, or their original characters.

    I'm still working on a good filter that stops all remaining SQL injection attacks. Right now I just duplicate all single quotes, but that's an ugly solution, and it may not be 100% safe.

  6. #6
    Non-Member
    Join Date
    Jan 2004
    Location
    Planet Earth
    Posts
    1,764
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Azmo - can you post your script for us all to have a look at please ?

    Thanks

  7. #7
    SitePoint Wizard
    Join Date
    Oct 2001
    Location
    Tucson, Arizona
    Posts
    1,858
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by DJ P@CkMaN
    I use something along these lines, usually just coded inline, not as a specific function.
    PHP Code:
     $string addslashes(htmlspecialchars(trim($source))); 
    Doesn't that get tedious for you?

  8. #8
    Ceci n'est pas Zoef Zoef's Avatar
    Join Date
    Nov 2002
    Location
    Malta
    Posts
    1,111
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    If the source is a form field I'll trim() it first.

    Then I check if the data is in a 'valid format', if it is not it is not accepted and apropriate action is taken.

    Btw, I make the distinction between 'valid' and 'valid format'. In 'articleId=459', 459 is of 'valid format' but if there is no such article then it is not 'valid'.

    If got a string of functions for this: isVfId(), isVfmd5String(), isVfStringPara, isVfEmail, etc... ('Vf' stands for, you guessed it... valid format). Some of these functions will use some of the others. I was thinking of putting all of this in a class somehow but I haven't yet.

    Then before putting things in the database (but only then) I'll use a wrapper function prepdata() which basically contains addslashes or mysql_escape_string. I use the wrapper function because at the time I couldn't make up my mind up which function to use and it should also help if I ever use anything else but mySql. I always have magic_quotes_gpc 'off' btw (They are evil you know )

    And when something is send to the screen (and only then) it gets the htmlentities treatment.

    Rik
    English tea - Italian coffee - Maltese wine - Belgian beer - French Cognac

  9. #9
    SitePoint Enthusiast Zero G's Avatar
    Join Date
    Jun 2002
    Location
    Ohio
    Posts
    63
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    This is in a file that is called by all of my pages before they do anything.

    PHP Code:
    foreach($_REQUEST AS $key => $val) {
      if (
    is_array($_REQUEST[$key])) {
       foreach(
    $_REQUEST[$key] AS $key2 => $val2) {
         
    $_REQUEST[$key][$key2] = trim($_REQUEST[$key][$key2]);
         
    $_REQUEST[$key][$key2] = addslashes($_REQUEST[$key][$key2]);
       }
      } else {
       
    $_REQUEST[$key] = trim($GLOBALS[$key]);
       
    $_REQUEST[$key] = addslashes($_REQUEST[$key]);
      }


  10. #10
    SitePoint Zealot
    Join Date
    Jun 2003
    Location
    Elsewhere
    Posts
    107
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Widow Maker
    Azmo - can you post your script for us all to have a look at please ?
    Nope, I can't. The code I currently use is too embarrassing to post on these forums: it's all based on an old idea I had for parsing strings of text and BBCode, which turned out to be messy, slow, and ugly. And apart from that, posting a single business class of my application would probably just confuse the crap out of everybody.

    Anywho.

    Here's a quicky Singleton thingy version of what I'm doing. It still has one problem: it can't handle multiple values for the same parameter yet.

    PHP Code:
    <?php
    // This code only works in PHP5

    class RequestParameter
    {
       private 
    $Parameter = array();

       private function 
    __construct()
       {
          
    $this->Clean$_GET'get' );
          
    $this->Clean$_POST'post' );
          
    $this->Clean$_COOKIE'cookie' );
       }

       private function 
    Clean$arrayData$arrayName )
       {
          
    $search_key  = array( '/</',    '/>/',    '/&/',     '/"/',      "/\n/" );
          
    $replace_key = array( '[lt]''[gt]''[amp]''[quot]''[br]' );

          foreach ( 
    $arrayData as $key => $value )
          {
             
    $value trim$value );

             if ( !
    is_numeric$value ) && !empty( $value ) )
             {
                
    $value preg_replace$search_key$replace_key$value );
             }

             
    $this->Parameter$arrayName ][ $key ] = $value;
          }
       }

       public function 
    Get$keyName$arrayName )
       {
          if ( isset( 
    $this->Parameter$arrayName ][ $keyName ] ) )
          {
             return( 
    $this->Parameter$arrayName ][ $keyName ] );
          }

          return( 
    false );
       }

       
    /// SINGLETON CODE ///

       
    private static $Instance false;

       public static function 
    GetInstance()
       {
          if ( 
    false === self::$Instance )
          {
             
    self::$Instance = new RequestParameter();
          }

          return( 
    self::$Instance );
       }
    }

    ?>
    Advantage of this solution: there's no risk of sanitizing the same characters more than once. If you use htmlentities() and htmlspecialchars() several times on the same string (I've seen this happen in a number of apps), you'll end up with strings like: &amp;amp;amp;amp;amp;amp;lt;

    Using BB tags for potentially dangerous characters has more advantages: it allows me to store all content in BB format, which can easily be transformed into many document types (HTML, XML, PDF, you name it). And it's very easy to add another character or string replacement to this central class, so if I ever read about some new input exploit, I'll be able to secure my entire application from a single point very quickly.

  11. #11
    SitePoint Author silver trophybronze trophy
    wwb_99's Avatar
    Join Date
    May 2003
    Location
    Washington, DC
    Posts
    10,625
    Mentioned
    4 Post(s)
    Tagged
    0 Thread(s)
    Did up me own BB Code object. Still pretty rough though, and completely undocumented. Took a slightly different approach than the above--it is a standalone object, so can be tossed stuff from anywhere. The other addition, which I dont think I have fully developed yet, is to implement the BBcode replacements using a rules object rather than the traditional array based approach. Seemed like it could be handy, and possibly estensible. In any case, here be the code for general inspiration:

    PHP Code:
    class PostParser
    {
        var 
    $RawPost;
        var 
    $Rules;
        var 
    $ConvertURLs;
        
        function 
    PostParser($RawPost,$ConvertURLs=true)
        {
            
    $this->RawPost=$RawPost;
            
    $this->Rules=array();
            
    $this->ConvertURLs=$ConvertURLs;
        }
        
        function 
    AddRule($Rule)
        {
            if (
    is_a($Rule,'ParsingRule')) {
                
    $this->Rules[]=$Rule;
            }
        }
        
        function 
    MakeParas($pee$br=1
        {
            
    $pee preg_replace("/(\r\n|\n|\r)/""\n"$pee); // cross-platform newlines
            
    $pee preg_replace("/\n\n+/""\n\n"$pee); // take care of duplicates
            
    $pee preg_replace('/\n?(.+?)(\n\n|\z)/s'"<p>$1</p>\n"$pee); // make paragraphs, including one at the end
            
    if ($br
                
    $pee preg_replace('|(?<!</p>)\s*\n|'"<br />\n"$pee); // optionally make line breaks
            
    return $pee;
        }
        
        function 
    MakeHyperlinks($text)
        {
        
    $search=array(
        
    '/(?<!"|href=|href\s=\s|href=\s|href\s=)(http|ftp|https):\/\/[\w]+(.[\w]+)([\w\-\.,@?^=%&:\/~\+#]*[\w\-\@?^=%&\/~\+#])?/i',
        
    '/(?<!"|href=|href\s=\s|href=\s|href\s=)(?<!:\/\/)www(.[\w]+)([\w\-\.,@?^=%&:\/~\+#]*[\w\-\@?^=%&\/~\+#])?/i'/**
    ,
        '/(?<!"|href=|href\s=\s|href=\s|href\s=|)[-\w+]*@[-a-z0-9]+(\.[-a-z0-9]+)*\.[a-z]{2,6}/i'
    //*/
                    
    );
            
    $replace=array(
                        
    '<a href="\0" target="_blank">\0</a>',
                        
    '<a href="http://\0" target="_blank">\0</a>'/**
    ,
                        '<a href="mailto:\0">\0</a>'
    //*/
                    
    );
            return 
    preg_replace($search,$replace,$text);
    /**
            print_r($replace);
            print_r($search);
            $ret=preg_replace($search,$replace,$text);
            $ret=preg_replace($search[1],$replace[1],$ret);
            $ret=preg_replace($search[2],$replace[2],$ret);
    //*/
            
    return $ret;
        }
        
        function 
    CleanupWordHTML($text)
        {
            
    $badwordchars=array(
                                
    145,
                                
    146,
                                
    147,
                                
    148,
                                
    151
                                
    );
            
    $fixedwordchars=array(
                                
    "'",
                                
    "'",
                                
    '&quot;',
                                
    '&quot;',
                                
    '&mdash;'
                                
    );
            return 
    str_replace($badwordchars,$fixedwordchars,$text);
        }
        
        function 
    ToHTML()
        {
            
    $ret=htmlentities($this->RawPost);
            
    $ret=$this->MakeParas($ret);
            if (
    count($this->Rules!=0)) 
            {
                
    $regex=array();
                
    $replace=array();
                foreach (
    $this->Rules as $rule)
                {
                    
    $regex[]=$rule->ToRegEx();
                    
    $replace[]=$rule->ToReplace();
                }
                
    ksort($regex);
                
    ksort($replace);
                
    $ret=preg_replace($regex,$replace,$ret);
            }
            if (
    $this->ConvertURLs)
                
    $ret=$this->MakeHyperlinks($ret);
            return 
    $ret;
        }

    }

    class 
    ParsingRule
    {
        var 
    $Tag;
        var 
    $HTMLTag;
        var 
    $Attribute;
        
        function 
    ParsingRule($Tag$HTMLTag$Attribute=false)
        {
            
    $this->Tag=$Tag;
            
    $this->HTMLTag=$HTMLTag;
            
    $this->Attribute=$Attribute;
        }
        
        function 
    ToRegEx()
        {
            if (
    $this->Attribute) {
                return  
    '/(\['.$this->Tag.'=(.+?)\])(.+?)(\[\/'.$this->Tag.'\])/i';
            }
            else
            {
                return 
    '/(\['.$this->Tag.'\])(.+?)(\[\/'.$this->Tag.'\])/i';
            }
        }
        
        function 
    ToReplace()
        {
            if (
    $this->Attribute) {
                return 
    '<'.$this->HTMLTag.' '.$this->Attribute.'\\2">\\3</'.$this->HTMLTag.'>';
            }
            else
                return 
    '<'.$this->HTMLTag.'>\\2</'.$this->HTMLTag.'>';
        }

    Implementation Example:
    PHP Code:
    $data='some string';
    $pp=new PostParser($data);
    $rule=new ParsingRule('b','strong');
    $pp->AddRule($rule);
    $rule=new ParsingRule('h','h1');
    $pp->AddRule($rule);
    $rule=new ParsingRule('link','a','target="_blank" href="');
    $pp->AddRule($rule);
    $rule=new ParsingRule('i','em');
    $pp->AddRule($rule);
    $rule=new ParsingRule('quote','blockquote');
    $pp->AddRule($rule);
    $rule=new ParsingRule('email','a','href="mailto:');
    $pp->AddRule($rule);
    echo 
    $pp->ToHTML(); 
    One question issue I did have was I never quite got the regex looking for email addresses to play right. Basically, I wanted it to convert a 'loose' email addy to a hyperlink. But I wanted it to ignore email addys already in tags. Any hints?

    WWB

  12. #12
    SitePoint Zealot
    Join Date
    Mar 2004
    Location
    New Jersey
    Posts
    140
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    wwb: If you're using PCRE, you can use negative lookaround assertions or word boundary assertions (\b).

    For instance, if your regex rule for email addresses were

    Code:
    /\w+@[\w.]+/U
    (very simple, i know), you could modify that to be

    Code:
    /(?<!mailto:)\w+@[\w.]+/U
    The (?<!mailto:) simple says to match that location if the 7 characters before it are not "mailto:". That should be find for the most part.

    Of course, you'll need a much better regex to match email addresses than the demonstrative one I provided.

  13. #13
    SitePoint Addict
    Join Date
    Apr 2002
    Posts
    330
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by mattjacob
    Having said that, what methods do you use to sanitize and disinfect user input? Do you use something as simple as the function below, or do you favor a full-blown set of classes--or something else?
    I use this Forms generation and validation class that besides the validation rules that prevent that forms with invalid values be acceptable comes with support to perform a sequence of clean up operations using regular expressions specified by the ReplacePatterns input definition argument.

    This argument can be used to perform consecutive substitutions that happen either on the client side with Javascript if possible right after the user changes the input value, or on the server side right before the form is validated.

    The example scripts demonstrate how to use this feature to reformat a URL field to cover for common misspellings but it can be used to sanitize practically any type of value based on static format rules.
    Manuel Lemos

    Metastorage - Data object relational mapping layer generator
    PHP Classes - Free ready to use OOP components in PHP

  14. #14
    SitePoint Zealot
    Join Date
    Mar 2004
    Location
    New Jersey
    Posts
    140
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    That's great Manuel.

  15. #15
    SitePoint Enthusiast robsynnott's Avatar
    Join Date
    Mar 2004
    Location
    Ireland
    Posts
    54
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by mattjacob
    It seems like the subject of data sanitization is hardly ever talked about in regards to PHP apps. This is troubling to me, since the majority of PHP projects are Web-oriented. And as we all know, the Web is a very dangerous place.

    Having said that, what methods do you use to sanitize and disinfect user input? Do you use something as simple as the function below, or do you favor a full-blown set of classes--or something else?

    PHP Code:
    function clean($string$length 255)
    {
        
    $cleaned strip_tags($cleaned);
        
    $cleaned substr($cleaned0$length);
        
    $cleaned addslashes($cleaned);


    Careful, it's entirely possible to end up with too many addslashes; do not apply indescriminately...
    http://ads.synnottsoftware.com
    Free Banner Text and Popup Exchange
    http://www.synnottsoftware.com/adsenseanalysis
    AdSense CSV Report analysis tool

  16. #16
    Hi there! Owen's Avatar
    Join Date
    Jan 2000
    Location
    CA
    Posts
    1,165
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I do something like:

    PHP Code:
    function myAS($st) {
            
    // strip out non-printable characters
            
    $st ereg_replace("[^[:print:]\n]"""$st);
            if (
    get_magic_quotes_gpc()==1)
                    return 
    $st;
            return 
    addslashes($st);

    I figure if people are uploading unprintable characters, they're probably up to no good. I also (int) everything that should be a number.

    Owen

  17. #17
    SitePoint Addict adam2003w's Avatar
    Join Date
    Mar 2004
    Location
    colorado
    Posts
    396
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    oh what a tangled web we weave

  18. #18
    SitePoint Wizard
    Join Date
    Oct 2001
    Location
    Tucson, Arizona
    Posts
    1,858
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by adam2003w
    oh what a tangled web we weave
    And the secret intelligent meaning behind that coment was...?

  19. #19
    Linux Junkie signlink's Avatar
    Join Date
    Feb 2003
    Location
    Annapolis
    Posts
    195
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Manuel is on phpclasses.org

    Quote Originally Posted by mlemos
    I use this Forms generation and validation class that besides the validation rules that prevent that forms with invalid values be acceptable comes with support to perform a sequence of clean up operations using regular expressions specified by the ReplacePatterns input definition argument.
    Look for his stuff here and the meta-language program here

    Really, Manuel, excellent work. I was working on a much less ambitious project with the same idea, but after looking at metastorage, I am going to save myself hours of work and just use that.

  20. #20
    Linux Junkie signlink's Avatar
    Join Date
    Feb 2003
    Location
    Annapolis
    Posts
    195
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I am now even more excited - he has an object factory class - creates classes based on your data structures... the only thing that bothers me is that I already spent so much time - I have to overcome internal laziness to force myself to start over with these new models ;-)

  21. #21
    SitePoint Enthusiast marcele's Avatar
    Join Date
    May 2004
    Location
    Edmonton
    Posts
    36
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Invision power board

    I found this usefull!!
    This is how they sanitize input on invision power board 2.0..

    PHP Code:
     <?php
     
    /**
     * CleanInputClass
     * @access public
     * @package includes/cleaninput/
     */
     
    class CleanInput {
     
         
    /**
         * @desc        Magic Quotes Check
         * @access     private
         * @var         string
         */
         
    var $get_magic_quotes 0;
         
         
         
    /**
         * @desc     Cleans Form elements
         * @return     string
         * @access     public
         */    
         
    function parseIncoming()
         {
             global 
    $HTTP_X_FORWARDED_FOR$HTTP_PROXY_USER$HTTP_CLIENT_IP;
             
             
    $this->get_magic_quotes get_magic_quotes_gpc();
             
             
    $return = array();
             
             if( 
    is_array($_GET) )
             {
                 while( list(
    $k$v) = each($_GET) )
                 {
                     if ( 
    is_array($_GET[$k]) )
                     {
                         while( list(
    $k2$v2) = each($_GET[$k]) )
                         {
                             
    $return$this->clean_key($k) ][ $this->clean_key($k2) ] = $this->clean_value($v2);
                         }
                     }
                     else
                     {
                         
    $return$this->clean_key($k) ] = $this->clean_value($v);
                     }
                 }
             }
             
             
    //----------------------------------------
             // Overwrite GET data with post data
             //----------------------------------------
             
             
    if( is_array($_POST) )
             {
                 while( list(
    $k$v) = each($_POST) )
                 {
                     if ( 
    is_array($_POST[$k]) )
                     {
                         while( list(
    $k2$v2) = each($_POST[$k]) )
                         {
                             
    $return$this->clean_key($k) ][ $this->clean_key($k2) ] = $this->clean_value($v2);
                         }
                     }
                     else
                     {
                         
    $return$this->clean_key($k) ] = $this->clean_value($v);
                     }
                 }
             }
             
             
    //----------------------------------------
             // Sort out the accessing IP
             //----------------------------------------
             
             
    $addrs = array();
             
             foreach( 
    array_reverseexplode','$HTTP_X_FORWARDED_FOR ) ) as $x_f )
             {
                 
    $x_f trim($x_f);
                 
                 if ( 
    preg_match'/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/'$x_f ) )
                 {
                     
    $addrs[] = $x_f;
                 }
             }
             
             
    $addrs[] = $_SERVER['REMOTE_ADDR'];
             
    $addrs[] = $HTTP_PROXY_USER;
             
    $addrs[] = $HTTP_CLIENT_IP;
             
             
    $return['IP_ADDRESS'] = $this->select_var$addrs );
             
             
    // Make sure we take a valid IP address        
             
    $return['IP_ADDRESS'] = preg_replace"/^([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})/""\\1.\\2.\\3.\\4"$return['IP_ADDRESS'] );        
             
    $return['request_method'] = strtolower($_SERVER['REQUEST_METHOD']);
             
             return 
    $return;
         }
         
         
    /**
         * @desc     Cleans Form elements
         * @return     string
         * @access     private
         * @var         String
         */
         
    function clean_key($key) {
             
             if (
    $key == "")
             {
                 return 
    "";
             }
             
    $key preg_replace"/\.\./"           ""  $key );
             
    $key preg_replace"/\_\_(.+?)\_\_/"  ""  $key );
             
    $key preg_replace"/^([\w\.\-\_]+)$/""$1"$key );
             
             return 
    $key;
         }
         
         
    /**
         * @desc     Cleans Form elements
         * @return     string
         * @access     private
         * @var         String
         */
         
    function clean_value($val)
         {
             
             if (
    $val == "")
             {
                 return 
    "";
             }
             
             
    $val str_replace" "" "$val );
             
    $val str_replacechr(0xCA), ""$val );  //Remove sneaky spaces    
             
    $val str_replace"&"            "&amp;"         $val );
             
    $val str_replace"<!--"         "<!--"  $val );
             
    $val str_replace"-->"          "-->"       $val );
             
    $val preg_replace"/<script/i"  "<script"   $val );
             
    $val str_replace">"            "&gt;"          $val );
             
    $val str_replace"<"            "&lt;"          $val );
             
    $val str_replace"\""           "&quot;"        $val );
             
    $val preg_replace"/\n/"        "<br />"        $val ); // Convert literal newlines
             
    $val preg_replace"/\\\$/"      "$"        $val );
             
    $val preg_replace"/\r/"        ""              $val ); // Remove literal carriage returns
             
    $val str_replace"!"            "!"         $val );
             
    $val str_replace"'"            "'"         $val ); // IMPORTANT: It helps to increase sql query safety.
             
             // Strip slashes if not already done so.        
             
    if ( $this->get_magic_quotes )
             {
                 
    $val stripslashes($val);
             }
             
             
    // Swop user inputted backslashes        
             
    $val preg_replace"/\\\(?!&amp;#|\?#)/""\", $val );
             
             return 
    $val;
         }
         
         /**
         * @desc     Variable Chooser
         * @return     string
         * @access     private
         * @var         array
         */
         function select_var(
    $array) {
             
             if ( !is_array(
    $array) ) return -1;
             
             ksort(
    $array);
                   
             
    $chosen = -1;  // Ensure that we return zero if nothing else is available
             
             foreach (
    $array as $k => $v)
             {
                 if (isset(
    $v))
                 {
                     
    $chosen = $v;
                     break;
                 }
             }        
             return 
    $chosen;
         }
     }
    It also gives you a safe IP address and request method

    Then you just call the class which goes through post and get vars..

    $safevars = array();

    //--------------------------------
    // Create Cleaninput Object
    //--------------------------------
    $cleanInput = new CleanInput;

    //--------------------------------
    // Set up our vars
    //--------------------------------
    $safevars = $cleanInput->parseIncoming();
    Last edited by marcele; Jul 5, 2004 at 13:35.

  22. #22
    SitePoint Addict
    Join Date
    Jul 2004
    Location
    The Caribbean
    Posts
    267
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    The problem with having one class/function for parsing your input data is that you need to escape/sanatize input in a different way depending on what you are going to do with it. For example, when inserting data into a database, you are likely to need addslashes(), but to use addslashes() when inserting into a text file may not make sense...

    Also, running addslashes, htmlspecialchars, or similar on the input for a user's password is probably not good since you will be changing the password string in certain cases.

    The point is, be careful what you do to input as it may have unexpected results...

  23. #23
    Non-Member
    Join Date
    Jan 2004
    Location
    Planet Earth
    Posts
    1,764
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    PHP Code:
    ...
    global 
    $HTTP_X_FORWARDED_FOR$HTTP_PROXY_USER$HTTP_CLIENT_IP;
    ... 
    Is no one worried about this huh ? No one ??

    And to think that there are folks out there using this software

    Okay, maybe no one could actually care about this point, but the use of GLOBALs is not even justified No excuse really

  24. #24
    simple tester McGruff's Avatar
    Join Date
    Sep 2003
    Location
    Glasgow
    Posts
    1,690
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I'm not sure if sanitisation is a good approach. Why would you want to silently clean up hacked user input? It is surely better to detect nasties rather than blindly sanitise. You then have the option to log the event and either 404 or set defaults (the former possibly being the better option on the grounds that programming errors can also lead to failed user input validation and hence the app has an element of self-testing).

    Many validation classes try to do way too much IMO. Initially, I think you just want to do some primary validation checks: ie check for alien or missing keys and some basic value checking (in ALL of G, P & C). Other, more complex rules should perhaps be carried out later by other classes.

    Escaping db strings would be the responsibility of classes performing db queries.

    I like to use ProxyArray objects in place of the GPC superglobals. These return filtered arrays (with any invalid values set null) as well as an errors array etc:

    ProxyArray
    +validate
    +hasValidKeys
    +hasValidValues
    +getCleanArray
    +getErrors

    A Firewall class (called at FrontController/PageController level) automatically creates these per request. Raw, unvalidated GPC need never be accessed in scripts.

  25. #25
    SitePoint Enthusiast marcele's Avatar
    Join Date
    May 2004
    Location
    Edmonton
    Posts
    36
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    globals

    Yes invision power uses globals all over the place... All his objects are instantiated in the main index.php and globalized in any functions... I don't see any real problem with that .... who runs with register globals enabled anymore anyway?

    I would never host on a server with register globals enabled...

    Quote Originally Posted by Widow Maker
    PHP Code:
     ...
     global 
    $HTTP_X_FORWARDED_FOR$HTTP_PROXY_USER$HTTP_CLIENT_IP;
     ... 
    Is no one worried about this huh ? No one ??

    And to think that there are folks out there using this software

    Okay, maybe no one could actually care about this point, but the use of GLOBALs is not even justified No excuse really


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
  •