How do I authenticate a user in PHP / MySQL?

前端 未结 7 1514
春和景丽
春和景丽 2020-12-08 09:26

So recently I learned how to properly add a username and password to a database. My database is usersys, and the table storing user information is called userdb. The table h

7条回答
  •  既然无缘
    2020-12-08 09:38

    I like to use both $_SESSION and MYSQL Checks with any login POST. This should help get a few things started.

    $username = mysql_real_escape_string($_POST[username]);
    $password = strip_tags($_POST[password]);
    $password = sha1($password);
    
    if(isset($username) && isset($password) && !empty($username) && !empty($password))
    {
    $sql = mysql_query("SELECT * FROM users_column WHERE username = '$username' AND password = '$password'");
    
    //Check the number of users against database
    //with the given criteria.  We're looking for 1 so 
    //adding > 0 (greater than zero does the trick). 
    $num_rows = mysql_num_rows($sql);
    if($num_rows > 0){
    
    //Lets grab and create a variable from the DB to register
    //the user's session with.
    $gid = mysql_query("SELECT * FROM users_column WHERE username = '$username' AND password = '$password'");
    $row = mysql_fetch_assoc($gid);
    $uid = $row[userid];
    
    // This is where we register the session.
    $_SESSION[valid_user] = $uid;
    
    //Send the user to the member page.  The userid is what the 
    //session include runs against.
    header('Location: memberpage.php?userid='.$userid);
    }
    
    //If it doesn't check out -- throw an error.
    else
    {
    echo 'Invalid Login Information';
    }
    }
    

    NOTE: You would need to start the page file with session_start() and create a separate Session Check include stating with session_start() and then your progressions e.g. if($_SESSION[valid_user] != $userid) do something.

提交回复
热议问题