2015-10-16 130 views
1

所以,我試圖實現以下內容: 當您進入該網站時,只有一個密碼框。如果您輸入的密碼與數據庫中的密碼相符,則會打開一個包含更多信息的彈出窗口。我會如何去做這件事?在Web數據庫中存儲密碼?

+0

您使用的是什麼Web服務器/應用程序? –

回答

0

讓我們打破你的問題:

  • 你需要一個索引頁,允許用戶登錄
  • 爲了讓用戶登錄,您將需要使用一個表格(最簡單的方法),或AJAX請求(稍微困難的方法)聯繫某種登錄功能。 (在我的例子中,我將使用PHP,但您可以根據需要使用其他語言。)
  • 在PHP腳本中,您需要能夠訪問數據庫。 (MySQLiPDO是當前爲此推薦的PHP類別。)
  • 一旦連接到數據庫,您將需要查詢數據庫以從表中獲取相關行。
  • 現在您需要從行中獲取數據並執行必要的檢查。
  • 最後,您需要將一些數據返回給瀏覽器,以便瀏覽器知道下一步該怎麼做。 (請確保您的代碼能夠回答以下問題:登錄是否成功?應該打開哪個彈出窗口?應該顯示什麼錯誤消息?應該設置哪些Cookie?等等)。

還有更多的網站登錄比這個,但這只是你的問題的一般故障。我將使用PHP作爲動態服務器端腳本 - 我將使用一些JavaScript(只是香草JS,而不是jQuery或其他變體)。我將使用一些JavaScript(只是香草JS,而不是jQuery或其他變體) )爲AJAX登錄請求。 顯然你可以隨意在你的實現中使用別的東西。

我會首先創建index.html如下:

<!DOCTYPE html> 
<html lang="en"> <!-- Assuming the language is English --> 
    <head> 
     <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> 
     <title>Some Snazzy Title for Login Page</title> 
     <script type="text/javascript" src="resources/js/functions.js"></script> 
     <!-- Any additional things you want to include in the head of the HTML page --> 
    </head> 
    <body> 
     <!-- Table is used here for formatting --> 
     <table id="LoginTable" style="margin-left:auto;margin-right:auto;"> 
      <tr> 
       <td>Username:</td> 
       <td><input type="text" name="username" id="username"></td> 
      </tr> 
      <tr> 
       <td>Password:</td> 
       <td><input type="password" name="password" id="password"></td> 
      </tr> 
     </table> 
     <br> 
     <!--- Button to call our JavaScript AJAX login function: --> 
     <button onclick="AttemptLogin();">Login</button> 
     <!--- Include links to things like register, forgot password, and etc. here --> 
    </body> 
</html> 

正如你會發現,我們包括外部JavaScript文件functions.js其位於資源/ JS/子目錄。因此,包括這個,你可以創建一個在同一目錄index.html稱爲資源文件夾,然後你會創建一個名爲JS資源文件夾內的文件夾。在完成這之後,我們就可以創建functions.js

/* Credits to Minko Gechev (blog.mgechev.com) for createXMLHttp() (I have made my own modifications to it, though.) */ 
function createXMLHttp(){ 
     //If XMLHttpRequest is available then using it 
    if (typeof XMLHttpRequest !== undefined) { 
     // XMLHttpRequest is a fairly standard class in most browsers for handling AJAX, but 
     // it's not defined in all browsers (including IE) 
     return new XMLHttpRequest; 
    } else if (window.ActiveXObject) { 
     // User is using Internet Explorer 
     // Now we'll try to use an array of various IE XML HTTP types to find the right one: 
     var ieXMLHttpVersions = ['Microsoft.XMLHTTP', 'MSXML2.XMLHttp.5.0', 'MSXML2.XMLHttp.4.0', 'MSXML2.XMLHttp.3.0', 'MSXML2.XMLHttp', 'Microsoft.XMLHttp']; 
     var xmlHttp; 

     // Look through the array and try to create the XMLHttp object 
     for (var i = 0; i < ieXMLHttpVersions.length; i++) { 
      try { 
       xmlHttp = new ActiveXObject(ieXMLHttpVersions[i]); 
       return xmlHttp; 
      } catch (e) { 
       // Do nothing with error 
      } 
     } 

     // Despite the fact that ActiveXObject is defined, none of the XMLHttp versions could be 
     // successfully created. The browser's JavaScript implementation is unknown and thus we cannot 
     // use AJAX for this. 
     return null; 
    }else{ 
     // This browser is unknown and it does not support any of the common XML HTTP classes. 
     // As such, we will not be able to AJAX for login through this. 
     return null; 
    } 
} 

function AttemptLogin(){ 
    // First we'll get the current timestamp which we'll append to the login link to prevent caching: 
    var timestamp = new Date().getTime(); 
    // Link to POST login data to (with cache-buster): 
    var url = "ajax/login_process.php?cachebuster=" + timestamp; 
    var username = encodeURIComponent(document.getElementById("username").value); 
    var password = encodeURIComponent(document.getElementById("password").value); 

    var PostRequestData = "u=" + username + "&p=" password"; 

    var xmlHttp = createXMLHttp(); 

    if(xmlHttp === null){ 
     // xmlHttp could not be successfully created 
     // Alert the user of this issue and recommend a browser upgrade 
     alert("An error occurred that prevented us from logging in.\nThis issue seems to have been caused by your browsers JavaScript implementation. Please consider updating your browser to the newest version or installing a different browser."); 
     // Exit the function prematurely 
     return; 
    } // Else, xmlHttp appears to have been created successfully 

    xmlHttp.open('POST', url, true); 
    xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); 

    // Code the callback function which will be executed after the request completes. 
    xmlHttp.onreadystatechange = function(){ 
     if(xmlHttp.readyState == 4 && xmlHttp.status == 200){ 
      // It seems like the request successfully executed 
      // Now we'll just need to check if the login was successful or not: 
      var respText = xmlHttp.responseText; 

      if(respText.indexOf("login success") > -1){ 
       // Now we'll open a popup window here: 
       window.open('info.phtml', 'More Information', 'height=400,width=400'); 
       // Info.phtml will do additional security checks before displaying the information, by the way. 
      }else{ 
       alert("Error: either the username does not exist or the is incorrect for the username provided.\nPlease try again."); 
      } 
     } 
    } 

    // Now that we have the request open, the request header is set, and the callback 
    // function is defined, we will finally send the actual login request to the login_process.php page: 
    xmlHttp.send(PostRequestData); 
} 

現在我們需要寫出來的代碼login_process.php。但在此之前,我們需要創建該文件的目錄。因此,在您將index.html文件放入同一個文件夾中,您應該創建一個名爲ajax的子目錄。現在我們寫login_process.php文件夾中有云:

<?php 
    // Start up a session so we can hold whether the user is logged in or not: 
    session_start(); 

    // To further prevent caching we'll use these headers: 
    header("Cache-control: no-store, no-cache, must-revalidate"); 
    header("Expires: " . gmdate("D, d M Y H:i:s", (time() + 2)) . " GMT"); 
    header("Date: " . gmdate("D, d M Y H:i:s") . " GMT"); 
    header("Pragma: no-cache"); 
    header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); 

    // Make sure the request is valid: 
    if($_SERVER['REQUEST_METHOD'] != 'POST'){ 
     die("Invalid request type"); 
    } 

    // Now let's do the login. 
    // First, connect to the database: 
    $mysqli = new mysqli("Your database host", "Your database username", "Your database password", "The database name"); 

    if($mysqli->connect_errno){ 
     die("Failed to connect to database"); 
    } 

    // Next we'll get the request parameters 
    $username = $_POST['u']; 
    $password = $_POST['p']; 

    // Now we need to clean the username so we can search the database for it 
    $safeUsername = $mysqli->real_escape_string($username); // Prevents SQL injection 

    // Next let's query to see if this username exists: 
    $result = $mysqli->query("SELECT * FROM `TableName` WHERE `username`='$safeUsername' LIMIT 1;"); 

    if($result->num_rows == 0){ 
     // The username is unknown. 
     // Close the database members and die with vague error message 
     $result->free(); 
     $mysqli->close(); 
     die("fail"); 
    } // Else, username exists 

    // Get this user's salts and password hash: 
    $row = $result->fetch_assoc(); 

    // Now that we have the results as a PHP keyed array, we do not need to keep 
    // the database open any longer. So we will now close the database connection and 
    // free the database-related objects from the memory. 
    $result->free(); 
    $mysqli->close(); 

    // Now pull out the database provided values to local variables (for convenience): 
    $passwordSalt_1 = $row['salt1']; 
    $passwordSalt_2 = $row['salt2']; 
    $passwordHash = strtolower($row['passHash']); // Hexdigest of users current password hash 

    // Hash the users password with the salt and see if the results match: 
    $userPasswordData = $passwordSalt_1 . $password . $passwordSalt_2; 
    $requestedPassHash = strtolower(hash('sha512', $userPasswordData)); 

    // Now we just need to see if the user's passHash in the database is the same as 
    // the hash we just generated via the password sent in the request: 
    $isLoggedIn = ($passwordHash == $requestedPassHash); 

    $_SESSION['logged_in'] = ($isLoggedIn ? '1' : '0'); 

    // Send back the login result to the AJAX callback function: 
    die(($isLoggedIn ? "login success" : 'fail')); 
?> 

現在所有我們留下的是編碼info.phtml(彈出網頁):

<?php 
    // Start up the session so we can access the session variables: 
    session_start(); 

    // We certainly don't want the browser to cache our webpage which should require login: 
    header("Cache-control: no-store, no-cache, must-revalidate"); 
    header("Expires: " . gmdate("D, d M Y H:i:s", (time() + 2)) . " GMT"); 
    header("Date: " . gmdate("D, d M Y H:i:s") . " GMT"); 
    header("Pragma: no-cache"); 
    header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); 

    // Now we'll simply check if the user is logged in by referencing the session: 
    if(!isset($_SESSION['logged_in']) || // Check if session variable is set 
     empty($_SESSION['logged_in']) || // Check if the variable isn't empty 
     ($_SESSION['logged_in'] != '1')){ // Check if the variable is anything other than the valid value 

     // If any of the above statements are true, we reach this code and the user is not properly logged in 
     // As such, we should display an error page message instead of displaying the page. 
     header($_SERVER["SERVER_PROTOCOL"] . " 418 I'm a teapot", true, 418); 
     /* Personal Note: I'm using 418 'I'm a teapot' here out of personal preference. 
      Technically the RFC has not defined a response code for telling a user that they need 
      to login to the website before accessing the page, but sending back a non-4xx response 
      does not seem reasonable. 4xx response codes tell the client that there was an error 
      with their request. Since this wasn't a server a error and the request did not go over 
      successfully, a level 4xx response is the most fitting. */ 

     die("Error: You need to login before accessing this page."); 
    } // Else, the user is logged in. Go ahead and show them the page. 
?> 

希望這幫助您設置您的網站。如果這有幫助,請不要忘記註冊。 (不要試圖乞求,但我確實花了很長時間寫下你的問題的答案:P)我沒有測試過提供的代碼,所以我確信整個過程中可能會有一些小錯誤。很明顯,您需要重寫代碼的某些部分以適應您的情況,但總的來說,應該讓您深入瞭解這類可以編碼的系統。

相關問題