1

我为 PHP 登录和注册系统编写了一些代码,唯一的问题是当用户登录时,他的用户名只是$_POST在他的个人资料页面上发布()。所以我的问题是:如何创建一个登录系统,当用户登录时,他的用户名不显示,但系统看到的是 Mysql 中的用户名并显示他的真实姓名?很抱歉解释模糊,但我真的不知道如何解释。

我的代码:(用于登录表单)

    session_start();
    $_SESSION['username'] = $_POST['username'];

    $con=mysql_connect("host", "user", "pass");

    mysql_select_db("db"); 

    $username=$_POST['username']; 
    $password=$_POST['password']; 

    $user=mysql_real_escape_string($username); 
    $pass=mysql_real_escape_string($password); 

    $query=mysql_query("SELECT * FROM login where 
    username='$user' AND  
    password='$pass' ");  

    $count=mysql_num_rows($query); 
    if($count==1)  
        /* $count checks if username and password are in same row */
    { 


 $hour = time() + 3600;   
    /* $hour sets cookie storage time for 1 hour */

    /* setcookie() function sets cookie after login */
 setcookie("username", $username, $hour);  
 setcookie("password", $password, $hour); 

 header("");  
    /* header() function redirect user to members page */
} 
else
{  
print " <link rel=\"stylesheet\" type=\"text/css\" href=\"css/global_profile.css\" />\n";
print "<h3>" . "Username or password is incorrect" . "</h3>"; 
} 
4

2 回答 2

2

在这里,我为您整理了一个简单的登录脚本(因为我很无聊;p),通过它进行扫描,也许它会引起一些兴趣,它使用 PDO 进行数据库连接,因为 mysql_ 函数很快就会被弃用。

<?php
session_start();

/**
 * Table
CREATE TABLE IF NOT EXISTS `login` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(100) DEFAULT NULL,
  `pass_hash` varchar(255) DEFAULT NULL,
  `pass_salt` varchar(255) DEFAULT NULL,
  `birthday` varchar(100) DEFAULT NULL,
  `firstname` varchar(100) DEFAULT NULL,
  `lastname` varchar(100) DEFAULT NULL,
  `email` varchar(100) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=0 ;

 */

//DB Stuff
define('DBHOST','127.0.0.1');
define('DBNAME','yourdb');
define('DBUSER','root');
define('DBPASS','toor');
//End Config:---


//Open a PDO Database connection
try {
    $db = new PDO("mysql:host=".DBHOST.";dbname=".DBNAME, DBUSER, DBPASS);
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}catch (Exception $e){
    die('Cannot connect to mySQL server.');
}


class Login{
    public $db;
    public $user;
    public $pass;
    public $error;
    // sha512
    public $algo = '$6';
    // Cost parameter, 25k iterations
    public $cost = '$rounds=25000$';

    function __construct(PDO $db){
        $this->db = $db;
        $this->global_salt = sha1($_SERVER['HTTP_HOST']);
    }

    function make_seed(){
        list($usec, $sec) = explode(' ', microtime());
        return (float) $sec + ((float) $usec * 100000);
    }

    function unique_salt(){
        $salt = null;
        mt_srand($this->make_seed());
        for($i=0;$i < mt_rand(1,10);$i++){
            $salt = sha1($this->global_salt.$salt.mt_rand().uniqid().microtime(true));
        }
        return substr($salt,0,16);
    }

    function hash($password){
        $this->salt = $this->unique_salt();
        $this->full_hash = crypt($password, $this->algo.$this->cost.$this->salt);
        $this->full_salt = substr($this->full_hash, 0, 33);
        $this->hashed_password = substr($this->full_hash, 33);
        return $this->full_hash;
    }

    /**
     * Validate the given crypto hash against the given password
     */
    function check_password($hash, $salt, $password){
        $hash = ($this->algo.$this->cost.$salt.'$'.$hash);
        if($hash == crypt($password, substr($hash, 0, 33))){
            //Regenerate new hash and salt for given password
            $this->update_keys();
            $this->status = true;
            $_SESSION['logged_in'] = true;
            $_SESSION['username'] = $this->user;
            return true;
        }else{
            $this->status = false;
            return false;
        }
    }

    function process_login(){
        if($_SERVER['REQUEST_METHOD']=='POST'){

            $this->user   = (isset($_SESSION['userParam']) && isset($_POST[$_SESSION['userParam']]))?$_POST[$_SESSION['userParam']]:null;
            $this->pass   = (isset($_SESSION['passParam']) && isset($_POST[$_SESSION['passParam']]))?$_POST[$_SESSION['passParam']]:null;
            $this->create = (isset($_SESSION['createParam']) && isset($_POST[$_SESSION['createParam']]))?$_POST[$_SESSION['createParam']]:null;

            $cont = true;
            if($this->user == null || strlen($this->user) <= 2){$this->set_error('user','Please enter a username!'); $cont=false;}
            if($this->pass == null || strlen($this->pass) <= 2){$this->set_error('pass','Please enter a password!'); $cont=false;}

            if($cont==true){
                //Alls good continue
                if($this->create != null && $this->create=='1'){
                    //Check user for new account
                    if($this->check_user()==true){$this->set_error('user','Username already taken.');return;}
                    //Create account
                    $this->create_account();
                }else{
                    $this->check_login();
                }
            }else{
                //Error with form
                $this->set_error('global','Please fill in login form!');
            }
        }
    }

    function check_user(){
        $sql = 'SELECT 1 FROM login WHERE username=:username';
        $statement = $this->db->prepare($sql);
        $statement->bindParam(':username', $this->user, PDO::PARAM_STR);
        $statement->execute();
        $result = $statement->fetch(PDO::FETCH_ASSOC);

        if(!empty($result)){return true;}else{return false;}
    }

    function check_login(){
        $sql = 'SELECT pass_hash, pass_salt FROM login WHERE username=:username';
        $statement = $this->db->prepare($sql);
        $statement->bindParam(':username', $this->user, PDO::PARAM_STR);
        $statement->execute();
        $result = $statement->fetch(PDO::FETCH_ASSOC);

        $this->check_password($result['pass_hash'], $result['pass_salt'], $this->pass);
    }

    function create_account(){
        //Create new account
        $this->hash($this->pass);
        $sql = 'INSERT into login (username, pass_hash, pass_salt) VALUES (:username, :pass_hash, :pass_salt)';
        $statement = $this->db->prepare($sql);
        $statement->bindParam(':username', $this->user, PDO::PARAM_STR);
        $statement->bindParam(':pass_hash', $this->hashed_password, PDO::PARAM_STR);
        $statement->bindParam(':pass_salt', $this->salt, PDO::PARAM_STR);
        $statement->execute();

        $this->status = true;
        $_SESSION['logged_in']=true;
    }

    function update_keys(){
        //Update account password hash & salt
        $this->hash($this->pass);
        $sql = 'UPDATE login SET pass_hash=:pass_hash, pass_salt=:pass_salt WHERE username=:username';
        $statement = $this->db->prepare($sql);
        $statement->bindParam(':username', $this->user, PDO::PARAM_STR);
        $statement->bindParam(':pass_hash', $this->hashed_password, PDO::PARAM_STR);
        $statement->bindParam(':pass_salt', $this->salt, PDO::PARAM_STR);
        $statement->execute();

        $this->status = true;
        $_SESSION['logged_in']=true;
    }

    function get_user_info(){
        $sql = "SELECT birthday,firstname,lastname,email FROM `login` WHERE username = :username";
        $sql = $this->db->prepare($sql);
        $sql->bindParam(':username', $_SESSION['username'], PDO::PARAM_STR);
        $sql->execute();
        return $sql->fetch(PDO::FETCH_ASSOC);
    }

    static function logout(){
        unset($_SESSION['logged_in']);
        session_regenerate_id(true);
        exit(header('Location: ./index.php'));
    }

    function set_error($type,$value){
        $this->error[$type]=$value;
    }

    function error($type){
        echo (isset($this->error[$type]))?$this->error[$type]:null;
    }

}//END Login class

//Logout handler
if(isset($_GET['logout'])){ Login::logout(); }

$login = new Login($db);

//Login handler
$login->process_login();

//Check login status
if(isset($_SESSION['logged_in']) && $_SESSION['logged_in']==true){
    //Logged in
    $userinfo = $login->get_user_info();
    echo '<h1>Welcome,'.$userinfo['firstname'].'</h1>';
    echo '<pre>'.print_r($userinfo,true).'</pre>';
    echo '<p><a href="?logout">Logout</a></p>';

}else{
    //Not Logged In
    //Show login form & create uniqie parrams for user/pass/create post keys
    $_SESSION['userParam']   = sha1(uniqid().microtime(true));
    $_SESSION['passParam']   = sha1(uniqid().microtime(true));
    $_SESSION['createParam'] = sha1(uniqid().microtime(true));
?>
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Simple Login</title>
</head>

<body>
<h1>Please login:</h1>

<?php $login->error('global'); ?>

    <form method="POST" action="">
      <label for="user">Username :&nbsp; </label>
      <input type="text" name="<?=$_SESSION['userParam'];?>" size="29" required/> <?php $login->error('user'); ?>
      <br />
      <label for="pass">Password :&nbsp; </label>
      <input type="text" name="<?=$_SESSION['passParam'];?>" size="29"  required/> <?php $login->error('pass'); ?>
      <br />
      <input type="submit" value="Login">&nbsp; and create my account (demo):<input type="checkbox" name="<?=$_SESSION['createParam'];?>" value="1">
    </form>
</body>
</html>
<?php } ?>
于 2013-02-15T09:11:26.233 回答