国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Table of Contents
Reply content:
Home Backend Development PHP Tutorial How to prevent SQL injection?

How to prevent SQL injection?

Jul 06, 2016 pm 01:53 PM
mysql php information security Safety

  1. It was past 11 o’clock last night, and a friend suddenly came to me and told me that a vulnerability in their company’s website had been submitted to wooyun. (Then I briefly learned about the vulnerability with the girl. PS: The girl is a php programmer)

  2. Two vulnerabilities were submitted on wooyun, one of which is SQL injection(After understanding, the framework used by their company is an 11-year-old framework, or mysql_query()these old mysql functions) Another problem is the cookie. The girl wrote the user's uid and other sensitive information into the cookie, 2333. Then the uid used by PHP to process business logic is also taken from the cookie, 233333 (resulting in the ability to disguise as any user after modifying the cookie)

  3. I told her the solution to SQL injection (the first solution is to treat the symptoms but not the root cause, use regular expressions to match SQL statements, filter dangerous characters, keywords, escape symbols, the second solution is to abandon mysql Old function, use PDO or mysqli) (for the loophole in the cookie, I suggest that she store sensitive information such as uid in the session, and then encrypt the session ID and put it in the cookie)

  4. The girl finally said that she probably understood. It was unrealistic to change the mysql driver of the company framework. The company would not let her change it, so she had to use regular matching SQL statements to filter illegal strings. !

  5. I went online to find some SQL statement filtering functions. They are known to be very useful SQL filtering functions
    Answers from Zhihu aunties

I would like to discuss with you how to prevent SQL injection. Do you have any useful SQL injection functions to filter SQL statements? Share them. Thank you!

Reply content:

  1. It was past 11 o'clock last night, and a friend suddenly came to me and told me that a vulnerability in their company's website had been submitted to wooyun. (Then I briefly learned about the vulnerability with the girl. PS: The girl is a php programmer)

  2. Two vulnerabilities were submitted on wooyun, one of which is SQL injection(After understanding, the framework used by their company is an 11-year-old framework, or mysql_query()these old mysql functions) Another problem is the cookie. The girl wrote the user's uid and other sensitive information into the cookie, 2333. Then the uid used by PHP to process business logic is also taken from the cookie, 233333 (resulting in the ability to disguise as any user after modifying the cookie)

  3. I told her the solution to SQL injection (the first solution is to treat the symptoms but not the root cause, use regular expressions to match SQL statements, filter dangerous characters, keywords, escape symbols, the second solution is to abandon mysql Old function, use PDO or mysqli) (for the loophole in the cookie, I suggest that she store sensitive information such as uid in the session, and then encrypt the session ID and put it in the cookie)

  4. The girl finally said that she probably understood. It was unrealistic to change the mysql driver of the company framework. The company would not let her change it, so she had to use regular matching SQL statements to filter illegal strings. !

  5. I went online to find some SQL statement filtering functions. They are known to be very useful SQL filtering functions
    Answers from Zhihu aunties

I would like to discuss with you how to prevent SQL injection. Do you have any useful SQL injection functions to filter SQL statements? Share them. Thank you!

Why not use preprocessing? ? ? ? ? ? ? ? ? ?
Why not use preprocessing? ? ? ? ? ? ? ? ? ?
Why not use preprocessing? ? ? ? ? ? ? ? ? ?
Say important things three times!
SQL injection is already a thing of the last century!
If you don’t want to rewrite, you can use my simply packaged ready-made PHP classes, please choose one of them to use.
(I found that the code had some traces of my project, so I deleted the irrelevant code)
MySQLi version:

<code><?php
class DB
{
    var $Sql;
    var $Fetch;
    var $Param = array();
    
    public function __construct($Sql, $Fetch, $Param = array())
    {
        $this->sql = $Sql;
        $this->fetch = $Fetch;
        $this->param = $Param;
        //數(shù)據(jù)庫信息存放在配置文件里面,請自行修改成正確的路徑和值
        require($_SERVER['DOCUMENT_ROOT'] . '/configs/config.inc.php');
        $this->dbhost = & $DBHost;
        $this->dbuser = & $DBUser;
        $this->dbpw = & $DBPassword;
        $this->dbname = & $DBName;
    }
    
    public function Query()
    {
        $Mysqli = new mysqli($this->dbhost, $this->dbuser, $this->dbpw, $this->dbname);
        if ($Mysqli->connect_errno)
        {
            echo '無法連接數(shù)據(jù)庫';
            return false;
        }
        $Mysqli->query('SET NAMES UTF8');
        $Mysqli->begin_transaction(MYSQLI_TRANS_START_READ_ONLY);
        $Stmt = $Mysqli->stmt_init();
        $Stmt->prepare($this->sql);
        if (count($this->param) > 0)
        {
            $Type = '';
            for ($i = 0; $i < count($this->param); $i++)
            {
                if (is_double($this->param[$i]))
                {
                    $Type .= 'd';
                }
                else if (is_int($this->param[$i]))
                {
                    $Type .= 'i';
                }
                else if (is_string($this->param[$i]))
                {
                    $Type .= 's';
                }
                else
                {
                    $Type .= 'b';
                }
            }
            $RefArg = array($Type);
            for ($I = 0; $I < count($this->param); $I++)
            {
                $RefArg[] = & $this->param[$I];
            }
            call_user_func_array(array($Stmt, 'bind_param'), $RefArg);
        }
        if (!$Stmt->execute())
        {
            echo '讀取數(shù)據(jù)庫時發(fā)生錯誤:'. $Stmt->error;
            echo $this->sql;
            print_r($this->param);
            $Mysqli->rollback();            
            return false;
        }
        $Mysqli->commit();
        if (strtolower(substr($this->sql, 0, 6)) == 'select')
        {
            $this->res = $Stmt->get_result();
            $Stmt->free_result();
            return $this->GetRes();
        }
        else
        {
            $Stmt->free_result();
            return true;
        }
    }
    
    public function GetRes()
    {
        switch(strtolower($this->fetch))
        {
            case 'all':
                $row = $this->res->fetch_all();
                break;
            case 'array':
                $row = $this->res->fetch_array();
                break;
            case 'assoc':
                $row = $this->res->fetch_assoc();
                break;
            case 'field':
                $row = $this->res->fetch_field();
                break;
            case 'row':
                $row = $this->res->fetch_row();
                break;
            default:
                echo 'Please select a row return mode.';
                exit;
        }
        return $row;
    }
    
    public function NumRow()
    {
        if (isset($this->res))
        {
            return $this->res->num_rows;
        }
        else
        {
            return false;
        }
    }
}
?></code>

PDO_MYSQL version:

<code><?php
class DB
{
    var $SQL;
    var $Fetch;
    var $Param = array();
    
    public function __construct($SQL, $Fetch, $Param)
    {
        //數(shù)據(jù)庫信息存放在配置文件里面,請自行修改成正確的路徑和值
        require($_SERVER['DOCUMENT_ROOT'] . '/configs/config.inc.php');
        $this->DBHost = & $DBHost;
        $this->DBUser = & $DBUser;
        $this->DBPW = & $DBPassword;
        $this->DBName = & $DBName;
        $this->SQL = $SQL;
        $this->Fetch = $Fetch;
        $this->Param = $Param;
    }
    
    public function Query()
    {
        try
        {
            $Pdo = new PDO('mysql:host=' . $this->DBHost . ';dbname=' . $this->DBName, $this->DBUser, $this->DBPW);
            $Pdo->query('SET NAMES UTF8');
            $Pdo->beginTransaction();
            $Stmt = $Pdo->prepare($this->SQL);
            if (count($this->Param) > 0)
            {
                for ($I = 0; $I < count($this->Param); $I++)
                {
                    $Stmt->bindParam($I + 1, $this->Param[$I]);
                }
            }
            if (!$Stmt->execute())
            {
                echo '讀取數(shù)據(jù)庫時發(fā)生錯誤:' . $Stmt->errorinfo()[2];
                $Pdo->rollback();
                return false;
            }
            $Pdo->commit();
            if (strtolower(substr($this->SQL, 0, 6)) == 'select' || strtolower(substr($this->SQL, 0, 4)) == 'desc')
            {
                $this->Res = $Stmt;
                return $this->GetRes();
            }
            else
            {
                return true;
            }
        }
        catch (PDOException $e)
        {
            echo '無法連接數(shù)據(jù)庫';
            $Pdo->rollback();
            return false;
        }
    }
    
    public function GetRes()
    {
        switch(strtolower($this->Fetch))
        {
            case 'all':
                $Row = $this->Res->fetchAll(PDO::FETCH_ASSOC);
                break;
            case 'array':
                $Row = $this->Res->fetch(PDO::FETCH_BOTH);
                break;
            case 'assoc':
            case 'field':
                $Row = $this->Res->fetch(PDO::FETCH_ASSOC);
                break;
            case 'row':
                $Row = $this->Res->fetch(PDO::FETCH_NUM);
                break;
            default:
                echo 'Please select a row return mode.';
                exit;
        }
        return $Row;
    }
    
    public function NumRow()
    {
        if (isset($this->Res))
        {
            return $this->Res->num_rows;
        }
        else
        {
            return false;
        }
    }
}
?></code>

How to use:

<code>$DB = new DB(SQL語句, 結(jié)果集方式, array(要綁定的參數(shù));
$DB->Query();</code>

Attention! ! ! SQL statements use ? to replace the parameters to be queried! ! ! SQL injection vulnerabilities are caused by splicing variables into SQL statements! ! !
PS: If you can’t change the framework, then just go to bed. Time will only eliminate people who stick to the rules and outdated technologies.
Don’t expect regular filtering SQL statements to completely eliminate SQL injection. The reason why PHP7 abandoned the MySQL extension is because this extension has security holes!

I have written a similar summary before, so I won’t copy it. Commonly used Web security prevention suggestions are included (I will continue to add some omissions later), you can refer to: PHP Security Coding

A simple understanding is that if you can use PDO for preprocessing, use PDO. If you can't use PDO, use addslashes on top.

PHP system function has this addslashes(), you can try it

If you don’t use regular filtering, you can consider escaping.

In fact, the essence of preventing SQL injection is to escape or intercept sensitive characters in GPC foreign variables. GPC can be preprocessed in the framework entry file or route analysis class and then used for subsequent business use. This is relatively easy to implement and easy to implement. As for cookies, make a big change and use some encryption methods to check cookies. The encryption key can be placed in the session.

Well, the posture of this thing should be like this:

  1. Add some security services outside, such as Accelerator (we use Accelerator, the response is generally 100 milliseconds longer, there are occasional fluctuations, security is only basic, some posts and some XSS cannot be intercepted) )

  2. The server is equipped with web application firewall software

  3. Evaluation time, slowly migrate to pdo, and queries are bound with parameters (I personally think it is not that the change is not allowed, but that it takes time to arrange this)

Since PHP>=5.5 has abolished mysql_*, so for the sake of compatibility, we should take the time to reconstruct the framework.

Try www.oneasp.com

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to handle File Uploads securely in PHP? How to handle File Uploads securely in PHP? Jul 08, 2025 am 02:37 AM

To safely handle PHP file uploads, you need to verify the source and type, control the file name and path, set server restrictions, and process media files twice. 1. Verify the upload source to prevent CSRF through token and detect the real MIME type through finfo_file using whitelist control; 2. Rename the file to a random string and determine the extension to store it in a non-Web directory according to the detection type; 3. PHP configuration limits the upload size and temporary directory Nginx/Apache prohibits access to the upload directory; 4. The GD library resaves the pictures to clear potential malicious data.

How Do You Pass Variables by Value vs. by Reference in PHP? How Do You Pass Variables by Value vs. by Reference in PHP? Jul 08, 2025 am 02:42 AM

InPHP,variablesarepassedbyvaluebydefault,meaningfunctionsorassignmentsreceiveacopyofthedata,whilepassingbyreferenceallowsmodificationstoaffecttheoriginalvariable.1.Whenpassingbyvalue,changestothecopydonotimpacttheoriginal,asshownwhenassigning$b=$aorp

PHP find the position of the last occurrence of a substring PHP find the position of the last occurrence of a substring Jul 09, 2025 am 02:49 AM

The most direct way to find the last occurrence of a substring in PHP is to use the strrpos() function. 1. Use strrpos() function to directly obtain the index of the last occurrence of the substring in the main string. If it is not found, it returns false. The syntax is strrpos($haystack,$needle,$offset=0). 2. If you need to ignore case, you can use the strripos() function to implement case-insensitive search. 3. For multi-byte characters such as Chinese, the mb_strrpos() function in the mbstring extension should be used to ensure that the character position is returned instead of the byte position. 4. Note that strrpos() returns f

PHP header location ajax call not working PHP header location ajax call not working Jul 10, 2025 pm 01:46 PM

The reason why header('Location:...') in AJAX request is invalid is that the browser will not automatically perform page redirects. Because in the AJAX request, the 302 status code and Location header information returned by the server will be processed as response data, rather than triggering the jump behavior. Solutions are: 1. Return JSON data in PHP and include a jump URL; 2. Check the redirect field in the front-end AJAX callback and jump manually with window.location.href; 3. Ensure that the PHP output is only JSON to avoid parsing failure; 4. To deal with cross-domain problems, you need to set appropriate CORS headers; 5. To prevent cache interference, you can add a timestamp or set cache:f

Implementing Transactions and Understanding ACID Properties in MySQL Implementing Transactions and Understanding ACID Properties in MySQL Jul 08, 2025 am 02:50 AM

MySQL supports transaction processing, and uses the InnoDB storage engine to ensure data consistency and integrity. 1. Transactions are a set of SQL operations, either all succeed or all fail to roll back; 2. ACID attributes include atomicity, consistency, isolation and persistence; 3. The statements that manually control transactions are STARTTRANSACTION, COMMIT and ROLLBACK; 4. The four isolation levels include read not committed, read submitted, repeatable read and serialization; 5. Use transactions correctly to avoid long-term operation, turn off automatic commits, and reasonably handle locks and exceptions. Through these mechanisms, MySQL can achieve high reliability and concurrent control.

Handling character sets and collations issues in MySQL Handling character sets and collations issues in MySQL Jul 08, 2025 am 02:51 AM

Character set and sorting rules issues are common when cross-platform migration or multi-person development, resulting in garbled code or inconsistent query. There are three core solutions: First, check and unify the character set of database, table, and fields to utf8mb4, view through SHOWCREATEDATABASE/TABLE, and modify it with ALTER statement; second, specify the utf8mb4 character set when the client connects, and set it in connection parameters or execute SETNAMES; third, select the sorting rules reasonably, and recommend using utf8mb4_unicode_ci to ensure the accuracy of comparison and sorting, and specify or modify it through ALTER when building the library and table.

Connecting to MySQL Database Using the Command Line Client Connecting to MySQL Database Using the Command Line Client Jul 07, 2025 am 01:50 AM

The most direct way to connect to MySQL database is to use the command line client. First enter the mysql-u username -p and enter the password correctly to enter the interactive interface; if you connect to the remote database, you need to add the -h parameter to specify the host address. Secondly, you can directly switch to a specific database or execute SQL files when logging in, such as mysql-u username-p database name or mysql-u username-p database name

Managing Character Sets and Collations in MySQL Managing Character Sets and Collations in MySQL Jul 07, 2025 am 01:41 AM

The setting of character sets and collation rules in MySQL is crucial, affecting data storage, query efficiency and consistency. First, the character set determines the storable character range, such as utf8mb4 supports Chinese and emojis; the sorting rules control the character comparison method, such as utf8mb4_unicode_ci is case-sensitive, and utf8mb4_bin is binary comparison. Secondly, the character set can be set at multiple levels of server, database, table, and column. It is recommended to use utf8mb4 and utf8mb4_unicode_ci in a unified manner to avoid conflicts. Furthermore, the garbled code problem is often caused by inconsistent character sets of connections, storage or program terminals, and needs to be checked layer by layer and set uniformly. In addition, character sets should be specified when exporting and importing to prevent conversion errors

See all articles