login with username or email address in php

前端 未结 8 2279
面向向阳花
面向向阳花 2021-02-01 10:56

I am trying to create a login with username or email

My code is:

$username=$_REQUEST[\'login\'];
$email=$_REQUEST[\'login\'];
$password=$_REQUEST[\'passw         


        
相关标签:
8条回答
  • 2021-02-01 11:47
    $username=$_REQUEST['username'];//I'm assuming your code here was wrong
    $email=$_REQUEST['email'];//and that you have three different fields in your form 
    $password=$_REQUEST['password'];
    
    if (validate_username($username)) {
      $query="select * from  user_db where username='".$username".' and password='".validate_password($password)."'";
    } else if (validate_email($email)) {
      $query="select * from  user_db where email='".$email."' and password='".validate_password($password)."'";
    }
    
    //... elsewhere...
    
    function validate_username(&$username) {
      if (strlen($username) <= 1) { return false; }
      //return false for other situations
        //Does the username have invalid characters?
        //Is the username a sql injection attack?
      //otherwise...
      return true;
    }
    
    function validate_email(&$email) {
      //same deal as with username
    }
    
    function validate_password(&$password) {
      //same deal as with username
    }
    

    Note, if you have only two fields (login and password), then the distinction between email and username is meaningless. Further note that you should really be using PHP PDO to construct and execute your queries, to prevent security breaches and make your life waaay easier.

    0 讨论(0)
  • 2021-02-01 11:49

    The login parameter is the same for both email and username. Not exactly incorrect if you have a single login box that accepts either.

    You could put the condition in the query itself if you're not sure if it's an email or username.

    $login=$_REQUEST['login'];
    $query = "select * from  user_db where ( username='$login' OR email = '$login') and password='$password'"
    

    Edit: A PDO-like solution is much more preferred nowadays as the above is subject to SQL injection. The logic stays the same, but you'd have it look something like this:

    $query = "
        SET @username = :username
        SELECT * FROM user_db
           WHERE ( username = @username OR email = @username) 
           AND password = :password
    ";
    
    $statement = $pdoObject->prepare($query);
    $statement->bindValue(":username", $login, PDO::PARAM_STR);
    $statement->bindValue(":password", $password, PDO::PARAM_STR);
    $statement->execute();
    
    0 讨论(0)
提交回复
热议问题