Anti-MySQL Injection function

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

    Anti-MySQL Injection function

    SQL Injection is security failure of the most hacked sites...

    Here is Anti-MySQL Injection function:

    Code:
    function anti_injection($sql) {
       // removes words that contain sql syntax
       $sql = preg_replace(sql_regcase("/(from|select|insert|delete|where|drop table|show tables|#|\*|--|\\\\)/"),"",$sql);
       $sql = trim($sql); // strip whitespace
       $sql = strip_tags($sql); // strip HTML and PHP tags
       $sql = addslashes($sql); // quote string with slashes
       return $sql;
    }
    How to call the function:
    Code:
    <?php
    $query = anti_injection($query);
    ?>
    ... or when you "post" the data:
    Code:
    <?php
    $query = anti_injection($_POST['something']);
    ?>
    or another one i found

    if the topic was [HOW TO] Anti-SQL Injection Function I might have said that it did not depend on any given db, and there is a use for that, especially if you have SQL compliant functions for flat file, that said lets see what we can do to produce an anti-injection function the allows posting of (legal) SQL code in posts, and works irrelevant of SQL interface..

    .. after a bit of research I have the following, which covers all eventualities
    Code:
    <?php
    
    function anti_injection($sql,$debug=false) {
      if($sql=='') return;
    
      $single = false;   # do single quotes translation
      $double = false;   # do double quotes translation
    
    //  $sql = trim($sql); # strip whitespace *(what if the first line is space indented? ie ascii art)
    //  if (get_magic_quotes_gpc()) $sql = stripslashes($sql); # if you have problems with slashes
      $sql = htmlspecialchars($sql); # for < and >, &, single and double quote characters
    
      if(substr_count($sql,"'")==0) $single = false; else $single = true;
      if(substr_count($sql,'"')==0) $double = false; else $double = true;
    
      if($single) $sql = str_replace("'", '& #039;', $sql);  # for single quote characters
      if($double) $sql = str_replace('"', '&quote;', $sql); # for dpuble quote characters
    
      return $sql;
    }
    
    
    ?>
    the echo's are just for testing (eg: $safe_sql = anti_injection($data_to_be_sanitized,true);) , as these may be set differently on your PHP installation (not 110mb)

    (NOTE: when copying either of these PHP quoted code functions, change "& #039;" to read "&#039;" - minus space, its a quirk of the PHP code hiliter, it outputs "&#039;" as "&#038;#039;")

    that said, for pure speed I would use the following (less the comments)
    Code:
    <?php
    function anti_injection($sql) {
      $sql = htmlspecialchars($sql); # for < and >, &, single and double quote characters
      $sql = str_replace("'", '& #039;', $sql);  # for single quote characters (just in case)
      $sql = str_replace('"', '&quote;', $sql); # for dpuble quote characters (just in case)
    
      return $sql;
    }
    ?>
    or as antimatter might prefer
    Code:
    function sql_ai($sql){return str_replace('"','&quote;',str_replace("'", '&#039;',htmlspecialchars($sql)));}
    ________________
    Jacques
    jacques@gw-designs.co.za
    http://coding.biz.tm
    Come join and lets make it a place to learn all the noobies how to code
    __________________

    NEVER FORGET TO CLICK THE TANX BUTTON IF U LIKE WHAT IM SHARING OR HELPING WITH

    #2
    Thanks Nice Share

    Comment


      #3
      Lol yal stil on dis topic? LMAO.

      Comment


        #4
        mysql_real_string_escape() can be used to remove sql queries.
        e.g.
        PHP Code:
        $x=mysql_real_string_escape($x);; 
        Follow me @ksg91 | My Blog: http://ksg91.com | Nokia Blog: http://NokiaTips.in

        Comment


          #5
          tnx men,....


          http://www.toinx.org

          Comment


            #6
            Does this protect you site for the injector.

            Comment


              #7
              Originally posted by wap-lord View Post
              Does this protect you site for the injector.
              It will give you max security from Injection.

              PHP Code:
              $str mysql_real_escape_string($str); 

              Comment


                #8
                or a good way is how im doing my new script that means u have to re edit all the posts and gets
                PHP Code:

                function cleanQuery($string
                {
                 
                $badWords "(--)|(>)|(<)|(&)";
                 
                $string eregi_replace($badWords""$string);

                 
                $string mysql_real_escape_string($string); 

                return 
                $string;
                 }


                example:
                for 
                the gets


                getbrip
                ($sid);
                $action cleanQuery($_GET["action"]);
                $sid cleanQuery($_GET["sid"]);
                $page cleanQuery($_GET["page"]);
                $who cleanQuery($_GET["who"]);
                $uid getuid_sid($sid);

                or for 
                post

                $staftxt 
                cleanQuery($_POST["staftxt"]); 
                Last edited by ozziemale31; 13.08.10, 14:51.









                Dont Ask Me Dumb Questions.Or you'l get a Dumb Answer..
                Want A Profesional Logo or Theme For Your wap site Pm Me.If I Have The Time Ill Make It For Free

                Comment


                  #9
                  u can name the function anything u want ? am i right for example
                  Code:
                  [COLOR=#000000][COLOR=#007700]function [/COLOR][COLOR=#0000BB]cantinjecthere[/COLOR][COLOR=#007700]([/COLOR][COLOR=#0000BB]$string[/COLOR][COLOR=#007700]) 
                  {
                   [/COLOR][COLOR=#0000BB]$badWords [/COLOR][COLOR=#007700]= [/COLOR][COLOR=#DD0000]"(--)|(>)|(<)|(&)"[/COLOR][COLOR=#007700];
                   [/COLOR][COLOR=#0000BB]$string [/COLOR][COLOR=#007700]= [/COLOR][COLOR=#0000BB]eregi_replace[/COLOR][COLOR=#007700]([/COLOR][COLOR=#0000BB]$badWords[/COLOR][COLOR=#007700], [/COLOR][COLOR=#DD0000]""[/COLOR][COLOR=#007700], [/COLOR][COLOR=#0000BB]$string[/COLOR][COLOR=#007700]);
                  
                   [/COLOR][COLOR=#0000BB]$string [/COLOR][COLOR=#007700]= [/COLOR][COLOR=#0000BB]mysql_real_escape_string[/COLOR][COLOR=#007700]([/COLOR][COLOR=#0000BB]$string[/COLOR][COLOR=#007700]); 
                  
                  return [/COLOR][COLOR=#0000BB]$string[/COLOR][COLOR=#007700];
                   }[/COLOR][/COLOR]
                  
                  usage eg 
                  [COLOR=#000000][COLOR=#0000BB]$action [/COLOR][COLOR=#007700]= cantinjecthere[/COLOR][COLOR=#0000BB][/COLOR][COLOR=#007700][/COLOR][/COLOR][COLOR=#000000][COLOR=#0000BB][/COLOR][COLOR=#007700][/COLOR][COLOR=#0000BB][/COLOR][COLOR=#007700][/COLOR][COLOR=#0000BB][/COLOR][COLOR=#007700][/COLOR][COLOR=#DD0000][/COLOR][COLOR=#007700][/COLOR][/COLOR][COLOR=#000000][COLOR=#007700]([/COLOR][COLOR=#0000BB]$_GET[/COLOR][COLOR=#007700][[/COLOR][COLOR=#DD0000]"action"[/COLOR][COLOR=#007700]]);[/COLOR][/COLOR]
                  am i right ?
                  Wapchat4u


                  Topsites4u

                  Comment


                    #10
                    yep but i would recommend using preg_replace instead of eregi_replace as its been deprecated since php 5.3.0

                    Comment


                      #11
                      yep thats right

                      Added after 6 minutes:

                      a good read is this link below
                      SQL Injection Prevention Cheat Sheet - OWASP

                      Last edited by ozziemale31; 13.08.10, 16:10.









                      Dont Ask Me Dumb Questions.Or you'l get a Dumb Answer..
                      Want A Profesional Logo or Theme For Your wap site Pm Me.If I Have The Time Ill Make It For Free

                      Comment


                        #12
                        Updated

                        Code:
                        //////////////////////// Anti Sql hit...
                        function check_injection() 
                          { 
                            $badchars = array("DROP","TRUNCATE", "SELECT", "UPDATE", "DELETE" , "UNION", "WHERE", "FROM","INSERT","ORDER BY","'","perm","',","validated","',perm='4',validated='1'#"); 
                           
                            foreach($_REQUEST  as $value) 
                            { 
                              if(in_array(strtoupper($value), $badchars)) 
                              { 
                              $logfile= 'logs/log.txt'; //chmod 777 
                        $IP = $_SERVER['REMOTE_ADDR']; 
                        $logdetails= date("F j, Y, g:i a") . ': ' . '<a href=http://dnsstuff.com/tools/city.ch?ip='.$_SERVER['REMOTE_ADDR'].' target=_blank>'.$_SERVER['REMOTE_ADDR'].'</a>'; 
                        $fp = fopen($logfile, "r+"); 
                        fwrite($fp, $logdetails, strlen($logdetails)); 
                        fclose($fp); 
                        
                               header('Location:antihack.fbi'); 
                        
                              } 
                              else 
                              { 
                                $check = preg_split("//", $value, -1, PREG_SPLIT_OFFSET_CAPTURE); 
                        foreach($check as $char)
                        {
                        if(in_array(strtoupper($char), $badchars))
                        {
                              $logfile= 'logs/log.txt'; 
                        $IP = $_SERVER['REMOTE_ADDR']; 
                        $logdetails= date("F j, Y, g:i a") . ': ' . '<a href=http://dnsstuff.com/tools/city.ch?ip='.$_SERVER['REMOTE_ADDR'].' target=_blank>'.$_SERVER['REMOTE_ADDR'].'</a>'; 
                        $fp = fopen($logfile, "r+"); 
                        fwrite($fp, $logdetails, strlen($logdetails)); 
                        fclose($fp); 
                        
                                    header('Location:http://go-to-hell.com'); 
                        }}}} 
                        }
                        echo check_injection() or check_injection();

                        or this check_injection();
                        Visit: Chat4u.mobi - The New Lay Of being a site of your dreams!
                        Visit: WapMasterz Coming Back Soon!
                        _______
                        SCRIPTS FOR SALE BY SUBZERO
                        Chat4u Script : coding-talk.com/f28/chat4u-mobi-script-only-150-a-17677/ - > Best Script for your site no other can be hacked by sql or uploaders.
                        FileShare Script : coding-talk.com/f28/file-wap-share-6596/ -> Uploader you will never regret buying yeah it mite be old now but it still seems to own others...
                        _______
                        Info & Tips
                        php.net
                        w3schools.com

                        Comment


                          #13
                          ave just changed eregi to preg and got errors
                          Wapchat4u


                          Topsites4u

                          Comment


                            #14
                            try:
                            PHP Code:
                            function unject($string){
                            return 
                            mysql_real_escape_string(preg_replace("/(--)|(>)|(<)|(&)/","",$string));
                             } 

                            Comment


                              #15
                              here is one bt need some editing :P

                              PHP Code:
                              function minimum_version($vercheck) {
                                  
                              $minver = (int)str_replace('.'''$vercheck);
                                  
                              $curver = (int)str_replace('.'''phpversion());
                                  if(
                              $curver >= $minver)
                                      return 
                              true;
                                  return 
                              false;
                              }

                              function 
                              getvar($var) {
                                  global 
                              $HTTP_GET_VARS;
                                  global 
                              $HTTP_POST_VARS;
                                  
                              $val "";
                                  if (
                              minimum_version('4.1.0')) { // when global variables changed
                                      
                              if (in_array($var,array_keys($_GET))) {
                                          
                              $val $_GET[$var];
                                      } else if (
                              in_array($var,array_keys($_POST))) {
                                          
                              $val $_POST[$var];
                                      }
                                  } else {
                                      if (
                              in_array($var,array_keys($HTTP_GET_VARS))) {
                                          
                              $val $HTTP_GET_VARS[$var];
                                      } else if (
                              in_array($var,array_keys($HTTP_POST_VARS))) {
                                          
                              $val $HTTP_POST_VARS[$var];
                                      }
                                  }

                                  
                              remove_magic_quotes($val);
                                  return 
                              $val;
                              }

                              /*
                               * This function removes slashes that may have been automatically
                               * inserted by PHP if one of magic_quotes_* is On.
                               *
                               * Code by gordon at kanazawa dot ac dot jp as posted on php.net.
                               * http://www.php.net/manual/en/function.get-magic-quotes-gpc.php
                               */
                              function remove_magic_quotes(&$x) {
                                  if (
                              is_array($x)) {
                                      while (list(
                              $key,$value) = each($x)) {
                                          if (
                              $valueremove_magic_quotes($x[$key]);
                                      }
                                  }else if (
                              ini_get('magic_quotes_sybase')) {
                                      
                              $x preg_replace("/''/""'"$x);
                                  } else if (
                              get_magic_quotes_runtime()) {
                                      
                              $x preg_replace("/\\\"/"'"'$x);
                                  } else if (
                              get_magic_quotes_gpc()) {
                                      
                              $x stripslashes($x);
                                  }

                              $album_id = getvar("album_id");

                              Comment

                              Working...
                              X