Home >Backend Development >PHP Tutorial >PHP and Mysql login features prevent SQL injection

PHP and Mysql login features prevent SQL injection

小云云
小云云Original
2018-02-27 10:40:051574browse

I recently learned about SQL injection and found that many people's login function uses the username and password entered by the user at the same time, combined into a SQL statement, and the query determines whether there is a result to determine whether the login can be performed. For example:


    #
    <?php  
    $username = $_POST[&#39;username&#39;];  
    $password = $_POST[&#39;password&#39;];  
    $sql = "select * from user where username=&#39;{$username}&#39; and password=&#39;{$password}&#39; ";  
    $this->db->query($sql);
This way It is easy to add ' or 1=1 -- injection to the username parameter. Although this is just an example, many frameworks are used nowadays. If you are not careful, the final combined statement will be similar to this. Let’s not talk about input parameter filtering, parameter binding, syntax analysis and other common methods to deal with SQL injection. We can change the judgment method:

    <?php  
    $username = $_POST[&#39;username&#39;];  
    $password = $_POST[&#39;password&#39;];  
    $sql = "select * from user where username=&#39;{$username}&#39; ";  
    $data = $this->db->query($sql);  
      
    ......  
      
    if($data[&#39;password&#39;] == $password){  
        //密码OK  
    }else{  
        //密码错误  
    }


In this way, the data is found first, and then PHP itself is used to determine whether the password matches. Does this solve the problem?

Related recommendations:

Recommended 10 methods to prevent sql injection

The above is the detailed content of PHP and Mysql login features prevent SQL injection. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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