2013-02-15 158 views
1

我爲PHP登錄和註冊系統做了一些代碼,唯一的問題是,當用戶登錄他的用戶名時,他只在他的個人資料頁上發佈($_POST)。所以我的問題是:如何創建一個登錄系統,當用戶登錄他的用戶名時不顯示,但系統在Mysql中查看用戶名並顯示他的真實姓名?對於模糊的解釋抱歉,但我並不真正知道如何解釋。PHP登錄/註冊系統與個人資料頁

我的代碼:(登錄表單)

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>"; 
} 
+0

你有一個數據庫,所有的用戶信息都準備好了嗎? – 2013-02-15 08:22:52

+0

是的,我有一個數據庫與用戶信息:生日,名字,姓氏,電子郵件,用戶名,密碼。 – HTMLboy001 2013-02-15 08:25:13

+0

您可以發表您正在處理的代碼,並請閱讀「如何發佈問題」,以便每個人都可以更輕鬆地回答您的問題。 – Shail 2013-02-15 08:26:00

回答

2

這裏爲你整理了一個簡單的登錄腳本(因爲im lil無聊; p),掃描它並且可能會有一些興趣,因爲mysql_函數很快就會使用PDO作爲數據庫連接將被棄用。

<?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 } ?> 
+0

不要加密密碼!他們應該使用密碼哈希散列,如bcrypt/scrypt。 – 2013-02-15 09:38:48

+0

@Jack更新; P – 2013-02-15 10:18:32

+0

Bcrypt使用'$ 2y $';除此之外,所有奇怪的鹽的計算是怎麼回事?鹽生成不應受外部數據影響,例如'HTTP_HOST'。 – 2013-02-15 10:36:11