2016-06-17 7 views
0

このことは本当に吹き飛んでしまいました。クライアントが自分のユーザ名を入力できるテキストボックスを持つページを設計したいと思っています。存在する場合、cookieを作成し、入力されたユーザー名を含むファイルに新しい行を追加しない場合は、別のページに置くように、locationn.htmlという名前のファイル内のユーザー名です。ファイルベースのユーザログインページを作る方法

これはこのコードのコードです。「unamec」はCookieの名前、「$ user」はユーザー名、「umname」はその値がページ自体に送信されるユーザー名テキストボックスの名前ですpostメソッドを使用します。

<?php 
if(isset($_POST["uname"])){ 
$user=$_POST["uname"]; 
$pass=$_POST["passs"]; 
$see=file_get_contents("locationn.html"); 
$lines=explode("\n",$see); 
foreach($lines as $line){ 
if($line == $user){ 
setcookie("unamec",$user,time()+86400,"/"); 
echo '<script>window.location="main.html";</script>'; 
} 
} 
} 
?> 
+0

だから質問は何ですか? – Epodax

+0

これは確かに可能です。問題は発生しますが、_ウィキ?_通常、データベースはそのようなものに使用されますが、データベースのアプローチは、ストレージバックエンドとしてテキストファイルを使用するよりはるかに高速で柔軟性があります。 – arkascha

+0

サイドノート:phpの 'file()'関数を見てください:http://php.net/manual/en/function.file.phpこれは、 'explode()'マニュアルを保存しています。行は配列に分かれています。 – arkascha

答えて

0

私はファイルからユーザー名の保存と取得を手伝うことができます。これを適応させ、セッション管理とカップルして目標を達成することができます。

<?php 
if($_SERVER['REQUEST_METHOD'] == 'POST') { 
    $username = isset($_POST['username']) ? $_POST['username'] : null; 
    if($username !== preg_replace('/[^a-zA-Z0-9]+/', '', $username)) 
     throw new Exception('Invalid username.'); 
    $userStore = new UserStore('/tmp/creds.txt'); 
    if(! $userStore->isStored($username)) { 
     if($userStore->storeUsername($username)) { 
      echo $username . ' stored.'; 
     } 
    } else { 
     echo $username . ' is on file.'; 
    } 
} 


class userStore 
{ 
    public $fp; 
    public $filename; 

    public function __construct($filename) 
    { 
     $this->filename = $filename; 
     if(!file_exists($this->filename)) 
      file_put_contents($this->filename, null); 
     $this->fp = fopen($this->filename, "r+"); 
    } 

    public function isStored($username) { 
     $username_exists = false; 

     if(! $size = filesize($this->filename)) 
      return false; 
     $contents = fread($this->fp, $size); 

     $lines = array_filter(explode("\n", $contents)); 
     foreach($lines as $line) { 
      if(trim($line) == $username) { 
       $username_exists = true; 
       break; 
      } 
     } 

     return $username_exists; 
    } 

    public function storeUsername($username) 
    { 
     $fp = $this->fp; 
     if (flock($fp, LOCK_EX)) { 
      fwrite($fp, "$username\n"); 
      fflush($fp); 
      flock($fp, LOCK_UN); 
     } else { 
      return false; 
     } 

     return true; 
    } 
} 
?> 
<form method='POST'> 
    <input type='text' name='username'> 
    <input type='submit' value='login'> 
</form> 
+0

私はあなたのコードから私の変数をトリミングするアイデアを持って感謝 –

関連する問題