2016-11-23 5 views
-1

パスワードをテキストファイルに保存することは安全ではありませんが、心配はいりません。セキュリティは私のここでの目標ではありません。これはhackmeのウェブサイトのようなものです。
だから、私はこれまでのところ、私はこの配列php login store password in txt

$logins = array('Example' => '123','test' => '123','simon' => '123'); 

と、この私はそれを作るだろうか声明

if (isset($logins[$Username]) && $logins[$Username] == $Password){ 
    /* Success: Set session variables and redirect to Protected page */ 
    $_SESSION['UserData']['Username']=$logins[$Username]; 
    header("location:index.php"); 
    exit; 
} 

場合があり、私はテキストファイルにユーザー名とパスワードを保存する方法を、知っておく必要がありますリストとして保存するのではなく、それらをテキストファイルに保存して、if文をテキストファイルで実行できますか?

+0

なぜ? –

+0

hackmeのウェブサイト –

+0

jsonを見てください... –

答えて

1

JSONの種類のものを作成し、配列として参照できます。したがって、最初にファイルを準備してください。 passwords.jsonの内容(またはpasswords.txt、あなたが欲しいものは何でもそれを呼び出す):

  • ファイルの内容を読む:

    {} 
    

    そして今、あなたは何をする必要があるかは、次のようです。

  • これらを解析して連想配列にします。
  • ユーザー名が存在するかどうかキーを確認します。
  • パスワードを確認してください。

だから、最終的には、コードは次のようなものになるだろう:

<?php 
    // Read the file. 
    $users = file_get_contents("passwords.json"); 
    // Convert into an associative array. 
    $users = json_decode($users); 
    // Get the input from the user. 
    $username = $_POST["username"]; 
    $password = $_POST["password"]; 
    // Check the validity. 
    if (array_key_exists($username, $users) && $users[$username] == $password) { 
     // Valid user. 
     $_SESSION["user"] = array($username, $password); 
    } else { 
     echo "Not Right!"; 
    } 
?> 

そして、あなたはユーザーを格納したい場合は、あなただけの反対のことを行う必要があります。

  1. ユーザー名とパスワードを取得します。
  2. 元のユーザーの一覧をアレイに読み込みます。
  3. 新しいユーザー名とパスワードを追加します。
  4. JSONに変換します。
  5. ファイルの中に保存します。

最終コード:

<?php 
    // Read the file. 
    $users = file_get_contents("passwords.json"); 
    // Convert into an associative array. 
    $users = json_decode($users); 
    // Get the input from the user. 
    $username = $_POST["username"]; 
    $password = $_POST["password"]; 
    // Store the new one into the array. 
    $users[$username] = $password; 
    // Convert back to JSON. 
    $users = json_encode($users); 
    // Put it into the file. 
    file_put_contents("passwords.json", $users); 
?>