2013-05-12 66 views
0

我想做一個簡單的登錄/註冊,但登錄不起作用,只與我的txt文件的最後一行,可能是因爲其他行包含' \ n'在每一行的結尾處,但之前有效,我不知道出了什麼問題......我需要做些什麼才能使其工作?這裏是我的代碼:Php登錄/註冊數據存儲在txt

的login.php:

<?php 
if(isset($_POST["name"]) && isset($_POST["password"])){ 
    $file = fopen('data.txt', 'r'); 
    $good=false; 
    while(!feof($file)){ 
     $line = fgets($file); 
     $array = explode(";",$line); 
     if($array[0]==$_POST["name"] && $array[1]==$_POST["password"]){ 
      $good=true; 
      break; 
     } 
    } 

    if($good){ 
     $message="Welcome"; 
    }else{ 
     $message="Try again"; 
    } 
    include 'message.html'; 
fclose($file); 
}else{ 
    include 'login.html'; 
} 
?> 

reg.php:

<?php 
if(isset($_POST["name"]) && isset($_POST["password"])){ 
    $f=fopen("data.txt","a"); 
    fputs($f,$_POST["name"].";".$_POST["password"]."\r\n"); 
    fclose($f); 
}else{ 
    include 'reg.html'; 
} 
?> 

這是data.txt中看起來的樣子:

Viktor;1234 
Eve;12345 
Cathlin;12356 
+0

請定義'not working'。你在期待什麼,你會得到什麼?順便說一下,該代碼不是一個很好的方式來做你想做的事情。 – 2013-05-12 19:46:59

+0

如果名稱和密碼組合正確,則應該寫出「歡迎」,如您所見。除了最後一行之外,我每次都會收到「再試一次」。 – wfmn17 2013-05-12 19:49:11

+0

我看到你編輯了你的問題,並用$ message替換$ uzenet。這是否解決了你的問題? – 2013-05-12 19:51:04

回答

1

使用trim()從字符串的開始和結尾去掉空格。 http://php.net/manual/en/function.trim.php

while(!feof($file)){ 
    $line = fgets($file); 

    list($user, $pass) = explode(';', $line); 

    if(trim($user) == $_POST['name'] && trim($pass) == $_POST['password']){ 
     $good=true; 
     break; 
    } 
}