بالا
 تعرفه تبلیغات




 دانلود نمونه سوالات نیمسال دوم 93-94 پیام نور

 دانلود نمونه سوالات آزمونهای مختلف فراگیر پیام نور

نمایش نتایج: از شماره 1 تا 8 از مجموع 8

موضوع: بررسی امنیت سایت در برنامه نویسی

  1. #1
    TAHA آواتار ها
    • 9,180
    مدير بازنشسته

    عنوان کاربری
    مدير بازنشسته
    تاریخ عضویت
    Mar 2009
    محل تحصیل
    PNU-CLUB
    شغل , تخصص
    PNU-CLUB
    رشته تحصیلی
    PNU-CLUB
    راه های ارتباطی

    Icon14 بررسی امنیت سایت در برنامه نویسی

    سلام
    با توجه به این که هر سایتی مطرحی که احتمال حمله و سو استفاده وجود داره نیازمند امنیت خواهد بود این تاپیک رو ایجاد کردم تا با کمک دوستان حرفه ای و هر کسی که اطلاعاتی در زمینه database, php , inject , sql script داره مسائل امنیتی در سایت و حفره های نفوذی رو بررسی کنیم (البته تا جایی که دست ماست : یعنی برنامه نویس سایت)

    بهتره خودم شروع کنم (البته با اجازه اساتید محترم):
    بنظر من اولین و اساسی ترین حمله ها در اینترنت از طریق sql injection صورت می گیره که با یکسری عملیات حرفه ای کدهای sql رو از طریق متود های get یا post در سرور sql اجرا می کنن.
    نمی خوام وارد بحث تخصصی این مبحث بشم چون می دونم حتی توی این فروم هم چند جا بحث شده اما یه function برای جلوگیری از inject نوشتم که برای دوستان میذارم (البته اگر ایرادی داشت دوستان می تونن تکمیلش کنن)
    PHP کد:
    کد:
    function sql_quote($string) 
        { 
          if(get_magic_quotes_gpc()) 
          { 
              return stripslashes($string); 
          } 
    
          //check if this function exists 
          if(function_exists( "mysql_real_escape_string" )) 
    
          { 
              return mysql_real_escape_string($string); 
          } 
    
         //for PHP version < 4.3.0 use addslashes 
    
         else 
         { 
              return addslashes($string); 
         }
        }


    این تابع کاراکترهایی که در sql حالت اجرایی دارند رو تبدیل به کاراکتر های معادل و یا غیر فعال می کنه:
    مثال: کاراکتر ' را به کاراکتر /' تبدیل می کنه.

  2. #2
    TAHA آواتار ها
    • 9,180
    مدير بازنشسته

    عنوان کاربری
    مدير بازنشسته
    تاریخ عضویت
    Mar 2009
    محل تحصیل
    PNU-CLUB
    شغل , تخصص
    PNU-CLUB
    رشته تحصیلی
    PNU-CLUB
    راه های ارتباطی

    پیش فرض

    برای جلوگیری از ورود کدهای html نیز می تونیم از تابع زیر استفاده کنیم تا تگ های html رو به معادل غیر اجرایی (فقط نمایشی ) تبدیل کنه
    مثال: > رو به &lt; تبدیل می کنه

    تابع:

    کد:
    function htmlspecialchars_uni($message)
    {
        $message = preg_replace("#&(?!\#[0-9]+;)#si", "&amp;", $message); // Fix & but allow unicode
        $message = str_replace("<","&lt;",$message);
        $message = str_replace(">","&gt;",$message);
        $message = str_replace("\"","&quot;",$message);
        return $message;
    }

  3. #3
    TAHA آواتار ها
    • 9,180
    مدير بازنشسته

    عنوان کاربری
    مدير بازنشسته
    تاریخ عضویت
    Mar 2009
    محل تحصیل
    PNU-CLUB
    شغل , تخصص
    PNU-CLUB
    رشته تحصیلی
    PNU-CLUB
    راه های ارتباطی

    Icon14

    یک کلاس session که سیشن ها رو برای کنترل بیشتر وامنیت بالاتر در دیتابیس ذخیره می کنه!
    PHP کد:
    کد:
    class dbSession
    {
    
        /**
         *  Constructor of class
         *
         *  Initializes the class and starts a new session
         *
         *  There is no need to call start_session() after instantiating this class
         *
         *  @param  integer     $gc_maxlifetime     the number of seconds after which data will be seen as 'garbage' and
         *                                          cleaned up on the next run of the gc (garbage collection) routine
         *
         *                                          Default is specified in php.ini file
         *
         *  @param  integer     $gc_probability     used in conjunction with gc_divisor, is used to manage probability that
         *                                          the gc routine is started. the probability is expressed by the formula
         *
         *                                          probability = $gc_probability / $gc_divisor
         *
         *                                          So if $gc_probability is 1 and $gc_divisor is 100 means that there is
         *                                          a 1% chance the the gc routine will be called on each request
         *
         *                                          Default is specified in php.ini file
         *
         *  @param  integer     $gc_divisor         used in conjunction with gc_probability, is used to manage probability
         *                                          that the gc routine is started. the probability is expressed by the formula
         *
         *                                          probability = $gc_probability / $gc_divisor
         *
         *                                          So if $gc_probability is 1 and $gc_divisor is 100 means that there is
         *                                          a 1% chance the the gc routine will be called on each request
         *
         *                                          Default is specified in php.ini file
         *
         *  @return void
         */
        //this function run 
        function dbSession($gc_maxlifetime = "600", $gc_probability = "", $gc_divisor = "")
        {
            global $settings;
            if($_COOKIE['rememberMe__ID_main'] == md5("3month"))
            {
                $gc_maxlifetime = 8035200;        
            }
            elseif($_COOKIE['rememberMe__ID_main'] == md5("6month"))
            {
                $gc_maxlifetime = 16070400;    
            }
            else
            {
                $gc_maxlifetime = $settings['session_lifetime'];
            }
            
            // if $gc_maxlifetime is specified and is an integer number
            if ($gc_maxlifetime != "" && is_integer($gc_maxlifetime)) {
            
                // set the new value
                @ini_set('session.gc_maxlifetime', $gc_maxlifetime);
                
            }
    
            // if $gc_probability is specified and is an integer number
            if ($gc_probability != "" && is_integer($gc_probability)) {
    
                // set the new value
                @ini_set('session.gc_probability', $gc_probability);
    
            }
    
            // if $gc_divisor is specified and is an integer number
            if ($gc_divisor != "" && is_integer($gc_divisor)) {
    
                // set the new value
                @ini_set('session.gc_divisor', $gc_divisor);
    
            }
             
            // get session lifetime
            $this->sessionLifetime = ini_get("session.gc_maxlifetime");
            
            // register the new handler
            session_set_save_handler(
                array(&$this, 'open'),
                array(&$this, 'close'),
                array(&$this, 'read'),
                array(&$this, 'write'),
                array(&$this, 'destroy'),
                array(&$this, 'gc')
            );
            
            register_shutdown_function('session_write_close');
            
            // start the session
            session_start();    
            
        }
        
        /**
         *  Deletes all data related to the session
         *
         *  @return void
         */          
        function stop()
        {
            $this->regenerate_id();
            session_unset();
            session_destroy();
        }
        
        /**
         *  Regenerates the session id.
         *
         *  <b>Call this method whenever you do a privilege change!</b>
         *
         *  @return void
         */
        function regenerate_id()
        {
    
            // saves the old session's id
            $oldSessionID = session_id();
            
            // regenerates the id
            // this function will create a new session, with a new id and containing the data from the old session
            // but will not delete the old session
            session_regenerate_id();
            
            // because the session_regenerate_id() function does not delete the old session,
            // we have to delete it manually
            $this->destroy($oldSessionID);
            
        }
        
        /**
         *  Get the number of online users
         *
         *  This is not 100% accurate. It depends on how often the garbage collector is run
         *
         *  @return integer     approximate number of users currently online
         */
        function get_users_online()
        {
          global $db;
         
            // counts the rows from the database
            $query = $db->simple_select(TABLE_PREFIX."session_data", $fields="COUNT(session_id) as count", $conditions="online_expire > ".time()."", $options=array());
            
            $result = $db->fetch_array($query);
            
            // return the number of found rows
            return $result["count"];
            
        }
        
        /**
         *  Custom open() function
         *
         *  @access private
         */
        function open($save_path, $session_name)
        {
        
            return true;
            
        }
        
        /**
         *  Custom close() function
         *
         *  @access private
         */
        function close()
        {
            return true;
        }
        
        /**
         *  Custom read() function
         *
         *  @access private
         */
        function read($session_id)
        {
          global $db;
    
            // reads session data associated with the session id
            // but only if the HTTP_USER_AGENT is the same as the one who had previously written to this session
            // and if session has not expired
           $result = $db->simple_select(TABLE_PREFIX."session_data", $fields="session_data", $conditions="session_id = '".$session_id."' AND http_user_agent = '".$_SERVER["HTTP_USER_AGENT"]."' AND session_expire > '".time()."'");
            
            // if anything was found
            if (is_resource($result) && @mysql_num_rows($result) > 0) {
    
                // return found data
                $fields = @mysql_fetch_assoc($result);
                // don't bother with the unserialization - PHP handles this automatically
                return $fields["session_data"];
                
            }
            
            // if there was an error return an empty string - this HAS to be an empty string
            return "";
            
        }
        
        /**
         *  Custom write() function
         *
         *  @access private
         */
        function write($session_id, $session_data)
        {
            global $db,$settings;
            // first checks if there is a session with this id
            
            $result = $db->simple_select(TABLE_PREFIX."session_data", $fields="session_data", $conditions="session_id = '".$session_id."'");
            
            // if there is
            if (@mysql_num_rows($result) > 0) {
    
                // update the existing session's data
                // and set new expiry time
                
              $array = array();
              $array['session_data'] = $session_data;
              $array['online_expire'] = (time() + $settings['online_expire_time_limit']);
              $array['session_expire'] = (time() + $this->sessionLifetime);
              $array['memberID'] = $_SESSION['memberID'];
              $array['request_URI'] = $_SERVER['REQUEST_URI'];
              $array['session_id'] = $session_id;
                
             $result = $db->update_query(TABLE_PREFIX."session_data", $array, $where="session_id = '".$session_id."'");
    
                
                // if anything happened
                if (@mysql_affected_rows()) {
                
                    // return true
                    return true;
                    
                }
    
            // if this session id is not in the database
            } else {
    
                // insert a new record
                $array = array();
                $array['session_id'] = $session_id;
                $array['http_user_agent'] = $_SERVER["HTTP_USER_AGENT"];
                $array['session_data'] = $session_data;
                $array['IP'] = $_SERVER['REMOTE_ADDR'];
                $array['online_expire'] = (time() + $settings['online_expire_time_limit']);
                $array['request_URI'] = $_SERVER['REQUEST_URI'];
                $array['session_expire'] = (time() + $this->sessionLifetime);
                
                $result = $db->insert_query(TABLE_PREFIX."session_data", $array);
                
                // if anything happened
                if (@mysql_affected_rows()) {
                
                    // return an empty string
                    return "";
                    
                }
                
            }
            
            // if something went wrong, return false
            return false;
            
        }
        
        /**
         *  Custom destroy() function
         *
         *  @access private
         */
        /* Destroy session record in database */ 
        function destroy($session_id) { 
            $session_sql = "DELETE FROM ".TABLE_PREFIX."session_data WHERE session_id = '$session_id'"; 
            $session_res = mysql_query($session_sql); 
            if (!$session_res) { 
                return false; 
            }         else { 
                return true; 
            } 
        } 
    
        
        /**
         *  Custom gc() function (garbage collector)
         *
         *  @access private
         */
        function gc($maxlifetime)
        {
          global $db;
          
            // it deletes expired sessions from database
            $result = $db->delete_query(TABLE_PREFIX."session_data", $where="session_expire < '".(time() - $maxlifetime)."'");
            
        }

    }

    دیتابیس:
    PHP کد:

    کد:
    CREATE TABLE IF NOT EXISTS `site_session_data` (
      `session_id` varchar(32) NOT NULL DEFAULT '',
      `http_user_agent` varchar(255) NOT NULL DEFAULT '',
      `session_data` longtext NOT NULL,
      `IP` varchar(20) NOT NULL,
      `memberID` bigint(20) NOT NULL,
      `request_URI` varchar(450) NOT NULL,
      `session_expire` int(11) NOT NULL DEFAULT '0',
      `online_expire` int(11) NOT NULL,
      PRIMARY KEY (`session_id`)
    ) ENGINE=MyISAM DEFAULT CHARSET=latin1;


    البته این کلاس مربوط به kernel من هست.
    برای استفاده باید برخی از توابع رو تغییر بدین مثل : simple_select update_query و...

  4. #4
    TAHA آواتار ها
    • 9,180
    مدير بازنشسته

    عنوان کاربری
    مدير بازنشسته
    تاریخ عضویت
    Mar 2009
    محل تحصیل
    PNU-CLUB
    شغل , تخصص
    PNU-CLUB
    رشته تحصیلی
    PNU-CLUB
    راه های ارتباطی

    Icon14

    ها رو در فایل core.php لود کنید:
    PHP کد:
    کد:
    // PHP5 with register_long_arrays off?
    if (!isset($HTTP_POST_VARS) && isset($_POST))
    {
        $HTTP_POST_VARS = $_POST;
        $HTTP_GET_VARS = $_GET;
        $HTTP_SERVER_VARS = $_SERVER;
        $HTTP_COOKIE_VARS = $_COOKIE;
        $HTTP_ENV_VARS = $_ENV;
        $HTTP_POST_FILES = $_FILES;
    
        // _SESSION is the only superglobal which is conditionally set
        if (isset($_SESSION)){
            $HTTP_SESSION_VARS = $_SESSION;
        } else {
          $HTTP_SESSION_VARS = array();
        }
    } 
    
    // PHP4.1 ?
    if (!isset($_POST) && isset($HTTP_POST_VARS))
    {
        $_POST = $HTTP_POST_VARS;
        $_GET = $HTTP_GET_VARS;
        $_SERVER = $HTTP_SERVER_VARS;
        $_COOKIE = $HTTP_COOKIE_VARS;
        $_ENV = $HTTP_ENV_VARS;
        $_FILES = $HTTP_POST_FILES;
    
        // _SESSION is the only superglobal which is conditionally set
        if (isset($HTTP_SESSION_VARS)){
            $_SESSION = $HTTP_SESSION_VARS;
        } else {
          $_SESSION = array();
        }
    } 
    
    if (!isset($_REQUEST))
      $_REQUEST = array_merge( $_GET, $_POST, $_COOKIE );  
    
    // _SESSION is the only superglobal which is conditionally set
    if (!(isset($_SESSION ))){ 
          $_SESSION = array();
    }
    
    // Delete Globals:  
     $da_kine_globals = array_merge($_GET, $_POST, $_COOKIE, $_SESSION);
     unset($da_kine_globals['da_kine_globals']);    
     while (list($var,$val) = @each($da_kine_globals)){
            unset($$var);
      } 
      unset($val);  
        unset($da_kine_globals);


  5. #5
    TAHA آواتار ها
    • 9,180
    مدير بازنشسته

    عنوان کاربری
    مدير بازنشسته
    تاریخ عضویت
    Mar 2009
    محل تحصیل
    PNU-CLUB
    شغل , تخصص
    PNU-CLUB
    رشته تحصیلی
    PNU-CLUB
    راه های ارتباطی

    Icon14

    این هم از کلاس safedata که می تونین توی فایل core لود کنید:
    PHP کد:
    کد:
    /* 
    Copyright (c) 2005, Matt Smith  
    All rights reserved.  
    
    Redistribution and use in source and binary forms, with or without  
    modification, are permitted provided that the following conditions  
    are met:  
    
      1. Redistributions of source code must retain the above copyright  
         notice, this list of conditions and the following disclaimer.  
    
      2. Redistributions in binary form must reproduce the above copyright  
         notice, this list of conditions and the following disclaimer in  
         the documentation and/or other materials provided with the distri-  
         bution.  
    
      3. Neither the copyright holders nor the contributors names may be  
         used to endorse or promote products derived from this software  
         without specific prior written permission.  
    
    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS  
    "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT  
    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS  
    FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE  
    COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,  
    INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,  
    BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;  
    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER  
    CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT  
    LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN  
    ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE  
    POSSIBILITY OF SUCH DAMAGE. 
    */ 
    
    /*  
    safedata.class.php -- version 1.0  
        A class that effectively disables both register_globals and magic_quotes.  
          
        It includes wrapper functions for MySQL / MySQLi's escape string  
        functions and for htmlentities / htmlspecialchars that allow you to use  
        both strings and arrays. 
          
        It can also help with HTML forms, so you can ensure that the submitted  
        form values are of the correct type (int, float, string, array).  
    
    License: 
        Berkeley Software Distribution (revised; 3-clause)  
    
    Requirements: 
        PHP 4 >= 4.1.0, PHP 5 
    
    Changes:  
        v1.0 (October 17, 2005) 
            - cleaned things up a bit.  
            - added: safedata::__init() - as part of the clean-up,  
                     safedata::mysqli_escape_string(), safedata::is_string()  
            - updated: safedata::gettype(), safedata::htmlentities_array(),  
                       safedata::htmlspecialchars_array()  
            - fixed: safedata::is_float() - should now be compatible  
                     with PHP 4 >= 4.1.0 and PHP 4 < 4.2.0  
            - renamed: safedata::fix_register_globals()        => safedata::__disable_register_globals() - internal  
                       safedata::fix_magic_quotes()            => safedata::__disable_magic_quotes() - internal  
                       safedata::_current_version()            => safedata::__version()  
                       safedata::_release_date()            => safedata::__release()  
                       safedata::htmlentities_array()        => safedata::htmlentities()  
                       safedata::htmlspecialchars_array()    => safedata::htmlspecialchars()  
            - legacy: safedata::htmlentities_array(), safedata::htmlspecialchars_array()  
        v0.3 (April 14, 2005)  
            - added: safedata::is_int(), safedata::is_float(), safedata::gettype(),  
                     safedata::_current_version(), safedata::_release_date()  
        v0.2 (April 7, 2005)  
            - safedata::mysql_escape_string() has a new argument, MySQL link_id.  
            - added: safedata::htmlentities_array(), safedata::htmlspecialchars_array()  
        v0.1 (April 3, 2005) 
            - initial release  
    
    Class Functions: 
        Internal Functions  
            - safedata::__init()  
                This is called at the end of this file, just outside of the class,  
                and sets up a couple things that safedata will use.  This function  
                also calls __disable_register_globals() and __disable_magic_quotes()  
                for you. 
            - safedata::__version()  
                Returns a string of the current version of safedata.  
            - safedata::__release(optional date_format)  
                Returns a string of the release date of safedata.  
                The default date_format is 'F d, Y' -- January 1, 2001  
    
        SQL-Safe Functions  
            - safedata::mysql_escape_string (string/array, optional link_identifier)  
                When used with PHP 4 >= 4.3.0, and PHP 5, mysql_real_escape_string()  
                will be used, otherwise, mysql_escape_string().  
                It can take both strings and arrays containing strings.  
            - safedata::mysqli_escape_string (string/array, reference mysqli)  
                An object-oriented mysqli_real_escape_string() wrapper for  
                both strings and arrays that contain strings.  
    
        HTML-Safe Functions  
            - safedata::htmlentities (string/array, optional quote_style, optional charset)  
            - safedata::htmlspecialchars (string/array, optional quote_style, optional charset)  
                A wrapper for htmlentities() and htmlspecialchars() that takes  
                both strings and arrays containing strings.  
            - [LEGACY] safedata::htmlentities_array  
                alias of safedata::htmlentities()  
            - [LEGACY] safedata::htmlspecialchars_array  
                alias of safedata::htmlspecialchars()  
    
        Form Validation Functions  
            - safedata::is_int (form_variable)  
                Tests if the form variable is a valid integer.  
            - safedata::is_float (form_variable)  
                Tests if the form variable is a valid float.  
            - safedata::is_string (form_variable)  
                Tests if the form variable is a valid string.  
            - safedata::gettype (form_variable)  
                Returns the form variable's type.  
                ('int', 'float', 'string', 'array', 'unknown')  
    
    How to use:  
        To automatically disable register_globals and magic_quotes, and enable the  
        use of safedata's helpful functions, simply include this class file at the  
        top of your script.  For example:  
            require_once('safedata.class.php'); 
          
        Then, you can use the methods of this class either statically:  
            $_POST = safedata::mysqli_escape_string ($_POST, &$mysqli);  
        or through an instantiated object:  
            $safedata = new safedata();  
            $_POST = $safedata->mysqli_escape_string ($_POST, &$mysqli);  
    
    Credits:  
        Created by Matt Smith and released under the BSD (3-clause) license --  
        this class is based on: 
          
        - The articles at the PHP Security Consortium  
            http://phpsec.org  
        - This ONLamp.com article, entitled "PHP Form Handling"  
            http://www.onlamp.com/pub/a/php/2004/08/26/PHPformhandling.html  
        - This NYPHP article  
            http://education.nyphp.org/phundamentals/PH_storingretrieving.php  
        - and PHP function comments at 
            http://php.net 
    
    */  
    
    class safedata 
    {  
    // Private/Internal Functions  
    
        function __init () 
        {  
            safedata::__disable_register_globals (); 
            safedata::__disable_magic_quotes (); 
             
            $phpversion = phpversion ();  
            $GLOBALS['__safedata__']['php4'] = version_compare ($phpversion, "5.0.0", "lt"); 
            $GLOBALS['__safedata__']['php420'] = version_compare ($phpversion, "4.2.0", "ge"); 
            $GLOBALS['__safedata__']['php430'] = version_compare ($phpversion, "4.3.0", "lt"); 
            $GLOBALS['__safedata__']['version'] = '1.0'; 
            $GLOBALS['__safedata__']['release'] = array ('month' => 10, 'day' => 17, 'year' => 2005); 
        }  
    
        // This gives the current version of the safedata class.  
        function __version ()  
        { 
            return $GLOBALS['__safedata__']['version']; 
        }  
         
        // This gives the release date of this version.  
        function __release ($datefmt = 'F d, Y') 
        {  
            extract ($GLOBALS['__safedata__']['release']);  
            return date ($datefmt, mktime (0, 0, 0, $month, $day, $year) ); 
        } 
    
        // A function to fix register_globals  
        function __disable_register_globals () 
        { 
            if ( ini_get ('register_globals') )  
            { 
                foreach ( array ('_ENV', '_REQUEST', '_GET', '_POST', '_COOKIE', '_SERVER') as $globalkey )  
                    foreach ( $GLOBALS[$globalkey] as $sub_globalkey => $sub_globalval )  
                        if ( isset ($GLOBALS[$sub_globalkey]) )  
                        { 
                            if ( $GLOBALS['__safedata__']['php4'] ) // PHP 4  
                                $unset_line = "if ( !is_a  (\$GLOBALS[\$sub_globalkey], 'safedata') ) { unset (\$GLOBALS[\$sub_globalkey]); }"; 
                            else // PHP 5 
                                $unset_line = "if ( !(\$GLOBALS[\$sub_globalkey] instanceof safedata) ) { unset (\$GLOBALS[\$sub_globalkey]); }"; 
                            eval ($unset_line);  
                        } 
                 
                ini_set ('register_globals', 0); 
            } 
        } 
         
        // NYPHP's fix_magic_quotes function  
        // http://education.nyphp.org/phundamentals/PH_storingretrieving.php  
        function __disable_magic_quotes ($var = NULL, $sybase = NULL) 
        { 
            // if sybase style quoting isn't specified, use ini setting  
            if ( !isset ($sybase) )  
            { 
                $sybase = ini_get ('magic_quotes_sybase'); 
            } 
         
            // if no var is specified, fix all affected superglobals  
            if ( !isset ($var) ) 
            {  
                // if magic quotes is enabled  
                if ( get_magic_quotes_gpc () ) 
                { 
                    // workaround because magic_quotes does not change $_SERVER['argv']  
                    $argv = isset($_SERVER['argv']) ? $_SERVER['argv'] : NULL;  
         
                    // fix all affected arrays  
                    foreach ( array ('_ENV', '_REQUEST', '_GET', '_POST', '_COOKIE', '_SERVER') as $var )  
                    { 
                        $GLOBALS[$var] = safedata::__disable_magic_quotes ($GLOBALS[$var], $sybase);  
                    } 
         
                    $_SERVER['argv'] = $argv; 
         
                    // turn off magic quotes, this is so scripts which  
                    // are sensitive to the setting will work correctly  
                    ini_set ('magic_quotes_gpc', 0); 
                } 
          
                // disable magic_quotes_sybase  
                if ( $sybase )  
                { 
                    ini_set ('magic_quotes_sybase', 0); 
                } 
          
                // disable magic_quotes_runtime  
                set_magic_quotes_runtime (0); 
                return TRUE; 
            }  
         
            // if var is an array, fix each element  
            if ( is_array ($var) ) 
            { 
                foreach ( $var as $key => $val )  
                { 
                    $var[$key] = safedata::__disable_magic_quotes ($val, $sybase); 
                } 
          
                return $var; 
            } 
         
            // if var is a string, strip slashes  
            if ( is_string ($var) ) 
            { 
                return $sybase ? str_replace ('\'\'', '\'', $var) : stripslashes ($var); 
            } 
         
            // otherwise ignore 
            return $var; 
        }  
    
    // SQL-Safe Functions  
    
        // A mysql_[real_]escape_string() wrapper for both strings and arrays.  
        function mysql_escape_string ($var, $link_id = NULL) 
        { 
            if ( is_array ($var) ) 
            { 
                foreach ($var as $key => $val)  
                    $var[$key] = safedata::mysql_escape_string ($val, $link_id);  
            } 
            else 
            { 
                if ( !is_numeric ($var) ) 
                {  
                    if ( $GLOBALS['__safedata__']['php430'] )  
                        return mysql_escape_string ($var); 
                    else  
                        return isset ($link_id) ? mysql_real_escape_string ($var, $link_id) : mysql_real_escape_string ($var); 
                } 
            } 
              
            return $var; 
        } 
    
        // An object-oriented mysqli_real_escape_string() wrapper for  
        // both strings and arrays. 
        function mysqli_escape_string ($var, $mysqli) 
        { 
            if ( is_array ($var) ) 
            { 
                foreach ($var as $key => $val)  
                    $var[$key] = safedata::mysqli_escape_string ($val, $mysqli); 
            } 
            else 
            {  
                if ( !is_numeric ($var) ) 
                    return $mysqli->real_escape_string ($var); 
            } 
              
            return $var; 
        } 
    
    // HTML-Safe Functions 
          
        // An htmlentities() wrapper for both strings and arrays.  
        function htmlentities ($var, $quote_style = ENT_COMPAT, $charset = 'ISO-8859-1')  
        { 
            if ( is_array ($var) ) 
            { 
                foreach ($var as $key => $val)  
                    $var[$key] = safedata::htmlentities ($val, $quote_style, $charset);  
            } 
            else 
            { 
                if ( !is_numeric ($var) ) 
                    return htmlentities ($var, $quote_style, $charset);  
            } 
             
            return $var; 
        }  
        // Legacy 
        function htmlentities_array ($var, $quote_style = ENT_COMPAT, $charset = 'ISO-8859-1')  
        { 
            return safedata::htmlentities ($var, $quote_style, $charset); 
        }  
         
        // An htmlspecialchars() wrapper for both strings and arrays.  
        function htmlspecialchars ($var, $quote_style = ENT_COMPAT, $charset = 'ISO-8859-1')  
        { 
            if ( is_array ($var) ) 
            { 
                foreach ($var as $key => $val)  
                    $var[$key] = safedata::htmlspecialchars ($val, $quote_style, $charset);  
            } 
            else 
            { 
                if ( !is_numeric ($var) ) 
                    return htmlspecialchars ($var, $quote_style, $charset);  
            } 
             
            return $var; 
        }  
        // Legacy 
        function htmlspecialchars_array ($var, $quote_style = ENT_COMPAT, $charset = 'ISO-8859-1')  
        { 
            return safedata::htmlspecialchars ($var, $quote_style, $charset); 
        }  
    
    // Form Validation Functions  
    
        // Tests for integer. 
        function is_int ($var) 
        {  
            if ( is_array ($var) || is_object ($var) ) 
                return false; 
              
            return ( $var == strval (intval ($var) ) ) ? true : false; 
        }  
    
        // Tests for float.  
        function is_float ($var) 
        { 
            if ( is_array ($var) || is_object ($var) ) 
                return false; 
              
            if ( $GLOBALS['__safedata__']['php420'] )  
                return ( $var == strval (floatval ($var) ) ) ? true : false;  
            else 
                return ( $var == strval (doubleval ($var) ) ) ? true : false; 
        }  
         
        // Tests for string.  
        function is_string ($var) 
        { 
            if ( is_array ($var) || is_object ($var) ) 
                return false; 
              
            return ( $var == strval ($var) ) ? true : false; 
        }  
    
        // Tests for variable type and returns it's type:  
        // 'int', 'float, 'string', 'array', or 'unknown' 
        function gettype ($var) 
        {  
            if ( safedata::is_int ($var) ) 
                return 'int';  
            elseif ( safedata::is_float ($var) ) 
                return 'float';  
            elseif ( safedata::is_string ($var) ) 
                return 'string';  
            elseif ( is_array ($var) ) 
                return 'array';  
            else 
                return 'unknown'; 
        }  
    
    } 
    
    // Initialize safedata  
    safedata::__init ();


  6. #6
    TAHA آواتار ها
    • 9,180
    مدير بازنشسته

    عنوان کاربری
    مدير بازنشسته
    تاریخ عضویت
    Mar 2009
    محل تحصیل
    PNU-CLUB
    شغل , تخصص
    PNU-CLUB
    رشته تحصیلی
    PNU-CLUB
    راه های ارتباطی

    Icon14

    کلاس capcha یا آنتی اسپم:



    کد:
    class  captchaZDR {
     
      var $UserString;
      var $font_path;
      
      function captchaZDR(){
          switch(rand(1,11))
            {
              case 1  : $this->font_path = '../images/fonts/architextregular.ttf';     break;
              case 2  : $this->font_path = '../images/fonts/ASTUTEI.ttf';             break;
              case 3  : $this->font_path = '../images/fonts/augie.ttf';                 break;
              case 4  : $this->font_path = '../images/fonts/BASSETI.ttf';             break;    
              case 5  : $this->font_path = '../images/fonts/BITMAP.ttf';             break;
              case 6  : $this->font_path = '../images/fonts/BITMAPW.ttf';             break;
              case 7  : $this->font_path = '../images/fonts/BOLSTER.ttf';                break;
              case 8  : $this->font_path = '../images/fonts/font.ttf';                  break;  
              case 9  : $this->font_path = '../images/fonts/freesans.ttf';             break;
              case 10 : $this->font_path = '../images/fonts/lockergnome.ttf';         break;
              case 11 : $this->font_path = '../images/fonts/mrph.ttf';                 break;   
              default : $this->font_path = '../images/fonts/font.ttf';                   break;      
            }  
      }
    
      function LoadPNG(){  
           $bgNUM = rand(1,8);
           $im = @imagecreatefrompng('../images/captcha_bank/bg'.$bgNUM.'.png'); /* Attempt to open */
           if (!$im) { 
               $im  = imagecreatetruecolor(150, 30); /* Create a blank image */
               $bgc = imagecolorallocate($im, 255, 255, 255);
               $tc  = imagecolorallocate($im, 0, 0, 0);
               imagefilledrectangle($im, 0, 0, 150, 30, $bgc);
               imagestring($im, 1, 5, 5, "Error loading $imgname", $tc);
           }
           return $im;
      }
        
      function drawElipse($image){
            for($i=0;$i<5;$i++){
                // choose a color for the ellipse
                $red         = rand(0,155);
                $green       = rand(0,155);
                $blue        = rand(0,155);
                $col_ellipse = imagecolorallocate($image, $red, $green, $blue);
                // draw the ellipse
                $cx = rand(50,250);
                $cy = rand(50,250);
                $cw = rand(30,250);
                $ch = rand(20,250);
                imageellipse($image, $cx, $cy, $cw, $ch, $col_ellipse);
            }
            
            foreach (range('A', 'Z') as $letter) {
                $red    = rand(0,155);
                $green  = rand(0,155);
                $blue   = rand(0,155);
                $col_ellipse  = imagecolorallocate($image, $red, $green, $blue);  
                $font_size    = 2; //rand(1,12);
                $x      = rand(0,400);
                $y      = rand(0,200);
                imagechar($image, $font_size, $x, $y, $letter, $col_ellipse);       
            } 
    
            foreach (range('0', '9') as $letter) {
                $red    = rand(0,155);
                $green  = rand(0,155);
                $blue   = rand(0,155);
                $col_ellipse  = imagecolorallocate($image, $red, $green, $blue);  
                $font_size    = 2; 
                $x      = rand(0,200);
                $y      = rand(0,100);
                imagechar($image, $font_size, $x, $y, $letter, $col_ellipse);                 
            }         
           
      }
      
      function task_string(){
      
             // create a image from png bank
            $image = $this->LoadPNG(); 
      
            $string_a = array("A","B","C","D","E","F","G","H","J","K",
                              "L","M","N","P","R","S","T","U","V","W","X","Y","Z",
                              "2","3","4","5","6","7","8","9");
      
            $width = 0;  
            for($i=0;$i<5;$i++)
            {
                $colour     = imagecolorallocate($image, rand(0,155), rand(0,155), rand(0,155));
                $font        = $this->font_path;
                $angle      = rand(-15,15);
                // Add the text
                $width_pos  = rand(20,30);
                $width      = $width  + $width_pos;
                $height     = rand(35,75);
                $temp       = $string_a[rand(0,25)];
                $this->UserString .= $temp;
                imagettftext($image, 26, $angle, $width, $height, $colour, $font, $temp);
                $width    = $width + 3;
                $height   = $height + 3;
                imagettftext($image, 26, $angle, $width, $height, $colour, $font, $temp);
    
            }
            
            $_SESSION['captcha'] = $this->UserString;
            
            return $image;
      }
      
      function task_sum(){
             // create a image from png bank
              $image    = $this->LoadPNG(); 
            
              $colour = imagecolorallocate($image, rand(0,155), rand(0,155), rand(0,155));
              $font   = $this->font_path;
              $angle  = rand(-15,15);
              // Add the text
              $width = rand(20,30);
              $height = rand(35,75);
              
              $number1 = rand(1,99);
              $number2 = rand(1,9);
      
    
              imagettftext($image, 26, $angle, $width, $height, $colour, $font, $number1);
              
              $colour = imagecolorallocate($image, rand(0,155), rand(0,155), rand(0,155));
              $width  += 45; 
              imagettftext($image, 26, 0, $width, $height, $colour, $font, '+');
      
              $colour   = imagecolorallocate($image, rand(0,155), rand(0,155), rand(0,155));
              $width   += 25; 
              $angle    = rand(-15,15);
              imagettftext($image, 26, $angle, $width, $height, $colour, $font, $number2.'=?');
      
              $this->UserString = $number1+$number2;  
              
              $_SESSION['captcha'] = $this->UserString;
      
              return $image;         
      }
    
      function task_deduction(){
             // create a image from png bank
              $image    = $this->LoadPNG(); 
            
              $colour = imagecolorallocate($image, rand(0,155), rand(0,155), rand(0,155));
              $font   = $this->font_path;
              $angle  = rand(-15,15);
              // Add the text
              $width = rand(20,30);
              $height = rand(35,75);
              
              $number1 = rand(1,99);
              $number2 = rand(1,9);
      
              imagettftext($image, 26, $angle, $width, $height, $colour, $font, $number1);
              
              $colour = imagecolorallocate($image, rand(0,155), rand(0,155), rand(0,155));
              $width  += 45; 
              imagettftext($image, 26, 0, $width, $height, $colour, $font, '-');
      
              $colour   = imagecolorallocate($image, rand(0,155), rand(0,155), rand(0,155));
              $width   += 25; 
              $angle    = rand(-15,15);
              imagettftext($image, 26, $angle, $width, $height, $colour, $font, $number2.'=?');
      
              $this->UserString = $number1-$number2;  
              
              $_SESSION['captcha'] = $this->UserString;
      
              return $image;         
      } 
     
      function display(){
           
            switch(rand(1,3))
            {
              case 1  : $image  = $this->task_string();     break;
              case 2  : $image  = $this->task_sum();        break;
              case 3  : $image  = $this->task_deduction();  break;
              
              default : $image  = $this->task_string();     break;      
            }
            
            $this->drawElipse($image);
            
            // output the picture
            header("Content-type: image/png");
            imagepng($image);  
      } 
    
      function check_result(){
        if($_SESSION['captcha']!=$_REQUEST['capt'] || $_SESSION['captcha']=='BADCODE')
        {        
            $_SESSION['captcha']='BADCODE';
            return false;
        } 
        else 
        {
              return true;
        }
      } 
    
    }


    نحوه استفاده:


    کد:
     $captcha = new captchaZDR();
       
       $captcha->display();


    نحوه چک کردن:


    کد:
    if(!$captcha->check_result()){
           $errors[] = $plang['err_antisam_captcha'];
        }


    البته باید بک گراندها و فونت هارو هم داشته باشید تا کار کنه!

  7. #7
    TAHA آواتار ها
    • 9,180
    مدير بازنشسته

    عنوان کاربری
    مدير بازنشسته
    تاریخ عضویت
    Mar 2009
    محل تحصیل
    PNU-CLUB
    شغل , تخصص
    PNU-CLUB
    رشته تحصیلی
    PNU-CLUB
    راه های ارتباطی

    Icon14

    یه تابع کاملتر برای چک کردن ورودی ها نوشتم که میتونید از این استفاده کنید . این کاملتره به نظرم:


    کد:
    function filter_html($what){      
      
     
       ///.. BASIC ASCII Entities with new Entity Names 
         $what = str_replace( "&#"           , "(^)-(^)"       , $what ); 
         $what = str_replace( "&"            , "&amp;"         , $what ); 
         $what = str_replace( ">"            , "&gt;"          , $what ); 
         $what = str_replace( "<"            , "&lt;"          , $what ); 
         $what = ereg_replace( "\""          , "&quot;"        , $what ); 
         $what = str_replace( "!"            , "!"         , $what ); 
         $what = str_replace( "'"            , "'"         , $what ); 
         $what = str_replace( "(^)-(^)"       , "&#"            , $what ); 
         $what = str_replace("`"             ,""               , $what ); 
         $what = ereg_replace("\n"        , "<br>"          , $what ); 
         $what = ereg_replace("\r"        , ""              , $what );        
    
         ///.. ISO 8859-1 Symbol Entities 
       $what = str_replace("¡"            , "&iexcl;"      , $what ); 
       $what = str_replace("¤"            , "&curren;"      , $what ); 
       $what = str_replace("¢"            , "&cent;"      , $what );  
       $what = str_replace("£"            , "&pound;"      , $what ); 
       $what = str_replace("€"            , "&euro;"      , $what );    
       $what = str_replace("¥"            , "&yen;"      , $what );    
       $what = str_replace("¦"            , "&brvbar;"      , $what ); 
       $what = str_replace("§"            , "&sect;"      , $what ); 
       $what = str_replace("©"            , "&copy;"      , $what );          
       $what = str_replace("¿"            , "&iquest;"      , $what ); 
       $what = str_replace("¶"            , "&para;"      , $what ); 
            
       ///.. ISO 8859-1 Character Entities 
       $what = str_replace("À"            , "&Agrave;"      , $what );      
       $what = str_replace("Á"            , "&Aacute;"      , $what );    
       $what = str_replace("Â"            , "&Acirc;"      , $what );     
       $what = str_replace("Ä"            , "&Auml;"      , $what );  
       $what = str_replace("Å"            , "&Aring;"      , $what );  
       $what = str_replace("Æ"            , "&AElig;"      , $what );        
       $what = str_replace("Ç"            , "&Ccedil;"      , $what ); 
       $what = str_replace("È"            , "&Egrave;"      , $what );    
       $what = str_replace("É"            , "&Eacute;"      , $what );  
       $what = str_replace("Ê"            , "&Ecirc;"      , $what );  
       $what = str_replace("Ë"            , "&Euml;"      , $what );      
       $what = str_replace("Ì"            , "&Igrave;"      , $what ); 
       $what = str_replace("Î"            , "&Icirc;"      , $what );      
       $what = str_replace("Ï"            , "&Iuml;"      , $what );    
       $what = str_replace("Ð"            , "&ETH;"      , $what ); 
       $what = str_replace("Ñ"            , "&Ntilde;"      , $what ); 
       $what = str_replace("Ò"            , "&Ograve;"      , $what ); 
       $what = str_replace("Ó"            , "&Oacute;"      , $what );    
       $what = str_replace("Ô"            , "&Ocirc;"      , $what );  
       $what = str_replace("Õ"            , "&Otilde;"      , $what );  
       $what = str_replace("Ö"            , "&Ouml;"      , $what );    
       $what = str_replace("Ø"            , "&Oslash;"      , $what );  
       $what = str_replace("Ù"            , "&Ugrave;"      , $what );    
       $what = str_replace("Ú"            , "&Uacute;"      , $what ); 
       $what = str_replace("Û"            , "&Ucirc;"      , $what ); 
       $what = str_replace("Ü"            , "&Uuml;"      , $what );  
       $what = str_replace("Ý"            , "&Yacute;"      , $what ); 
       $what = str_replace("Þ"            , "&THORN;"      , $what ); 
       $what = str_replace("ß"            , "&szlig;"      , $what ); 
       $what = str_replace("à"            , "&agrave;"      , $what );      
       $what = str_replace("á"            , "&aacute;"     , $what );    
       $what = str_replace("â"            , "&acirc;"      , $what );        
       $what = str_replace("à"            , "&aacute;"      , $what );  
       $what = str_replace("ä"            , "&auml;"      , $what ); 
       $what = str_replace("å"            , "&aring;"      , $what ); 
       $what = str_replace("æ"            , "&aelig;"      , $what );  
       $what = str_replace("ç"            , "&ccedil;"      , $what ); 
       $what = str_replace("è"            , "&egrave;"      , $what ); 
       $what = str_replace("é"            , "&eacute;"      , $what );  
       $what = str_replace("ê"            , "&ecirc;"      , $what ); 
       $what = str_replace("ë"            , "&euml;"      , $what );  
       $what = str_replace("ì"            , "&igrave;"      , $what );    
       $what = str_replace("í"            , "&iacute;"      , $what ); 
       $what = str_replace("î"            , "&icirc;"      , $what );      
       $what = str_replace("ï"            , "&iuml;"      , $what );  
       $what = str_replace("ð"            , "&eth;"      , $what ); 
       $what = str_replace("ñ"            , "&ntilde;"      , $what );    
       $what = str_replace("ò"            , "&ograve;"      , $what );    
       $what = str_replace("ó"            , "&oacute;"      , $what ); 
       $what = str_replace("ô"            , "&ocirc;"      , $what ); 
       $what = str_replace("õ"            , "&otilde;"      , $what );    
       $what = str_replace("ö"            , "&ouml;"      , $what ); 
       $what = str_replace("ø"            , "&oslash;"      , $what );  
       $what = str_replace("ù"            , "&ugrave;"      , $what );  
       $what = str_replace("ú"            , "&uacute;"      , $what ); 
       $what = str_replace("û"            , "&ucirc;"      , $what );      
       $what = str_replace("ü"            , "&uuml;"      , $what );      
       $what = str_replace("ý"            , "&yacute;"      , $what ); 
       $what = str_replace("þ"            , "&thorn;"      , $what ); 
       $what = str_replace("ÿ"            , "&yuml;"      , $what );    
    
       ///.. ISO 8859-1 Other Entities 
       $what = str_replace("Œ"            , "&OElig;"      , $what ); 
       $what = str_replace("œ"            , "&oelig;"      , $what ); 
       $what = str_replace("Š"            , "&Scaron;"      , $what ); 
       $what = str_replace("š"            , "&scaron;"      , $what ); 
       $what = str_replace("˜"            , "&tilde;"      , $what );              
       $what = str_replace("‘"            , "&lsquo;"      , $what ); 
       $what = str_replace("’"            , "&rsquo;"      , $what ); 
       $what = str_replace("‚"            , "&sbquo;"      , $what );  
    
       // for some really strange reason this is replacing all characters:
       $what = str_replace("Ã"            , "&Atilde;"      , $what );  
       $what = str_replace("ã"            , "&atilde;"      , $what );          
      
         return $what;        
    }


  8. #8
    TAHA آواتار ها
    • 9,180
    مدير بازنشسته

    عنوان کاربری
    مدير بازنشسته
    تاریخ عضویت
    Mar 2009
    محل تحصیل
    PNU-CLUB
    شغل , تخصص
    PNU-CLUB
    رشته تحصیلی
    PNU-CLUB
    راه های ارتباطی

    Icon14

    در ضمن تابع زیر رو زمانی میشه بکار برد که به ورودی اجازه کدهای html رو میدیم ولی اجازه ورود تگ های حساس رو منع می کنیم:


    کد:
    function filter_html_dangerous_tags($what){ 
         $what = str_replace( "<script>"        , "&lt;script&gt;"      , $what ); 
         $what = str_replace( "</script>"       , "&lt;/script&gt;"     , $what ); 
         $what = str_replace( "<object>"        , "&lt;object&gt;"      , $what ); 
         $what = str_replace( "</object>"       , "&lt;/object&gt;"     , $what );
         $what = str_replace( "<iframe>"        , "&lt;iframe&gt;"      , $what ); 
         $what = str_replace( "</iframe>"       , "&lt;/iframe&gt;"     , $what ); 
         $what = str_replace( "<frameset>"      , "&lt;frameset&gt;"    , $what ); 
         $what = str_replace( "<frameset>"      , "&lt;frameset&gt;"    , $what );
         $what = str_replace( "<frame>"         , "&lt;frame&gt;"       , $what ); 
         $what = str_replace( "</frame>"        , "&lt;/frame&gt;"      , $what ); 
         $what = str_replace( "<link>"          , "&lt;link&gt;"        , $what ); 
         $what = str_replace( "</link>"         , "&lt;/link&gt;"       , $what );
     return $what; 
    }


برچسب برای این موضوع

مجوز های ارسال و ویرایش

  • شما نمی توانید موضوع جدید ارسال کنید
  • شما نمی توانید به پست ها پاسخ دهید
  • شما نمی توانید فایل پیوست ضمیمه کنید
  • شما نمی توانید پست های خود را ویرایش کنید
  •