输入相同的用户名时出现PHP错误

时间:2015-12-18 23:04:35

标签: php forms passwords username

用户名和密码存储在文件中,如果用户名已经退出文件,它应该告诉用户他们不能使用该密码并重新加载页面。现在它没有这样做,即使我键入相同的用户名,它也会直接发送到commentsWall.php。我错过了什么?

<html>
<body>
<h1>Please enter your information to create a new login account</h1>
 <form method="post">
  Login Name:<input type = "text"  name = "name" value = "" required><br/>
  Password:<input type = "password" name = "pwd" value = "" required><br/>
  <input type = "submit" name="submit_btn" id = "submit" value = "submit"/>
 </form>
</body>
</html>

<?php
 session_start();
 if($_POST){
  $handle = fopen("accounts.txt", "r");
  if(isset($_POST['name'])){
     $username = $_POST['name'];
     $file = file_get_contents('accounts.txt');
     $search = $username . ",";
     if(strpos($file, $search) !== FALSE){
        echo 'name already used, choose another';
        header('Location: '.$_SERVER['PHP_SELF']);
     }
    fclose($handle);
  }
  if(isset($_POST['pwd'])){
     $password = $_POST['pwd'];
  }
  $text = $username . "," . $password . "\n";
  $fp = fopen("accounts.txt", 'a+') or die("Unable to open file!");
  if(fwrite($fp, $text)){
     echo "saved";
     fclose($fp);
     header("Location: commentWall.php");
  }
  else{
     echo "Unable to store credentials.";
     header('Location: '.$_SERVER['PHP_SELF']);
  }
}
?>

如果你想看看commentsWall.php代码只是问,但我认为没有必要包括。

2 个答案:

答案 0 :(得分:0)

至少您需要重新构建代码,以便除非没有POST或登录失败,否则您不会发送登录表单。

<?php
 session_start();
 if($_POST){
  $handle = fopen("accounts.txt", "r");
  if(isset($_POST['name'])){
     $username = $_POST['name'];
     $file = file_get_contents('accounts.txt');
     $search = $username . ",";
     if(strpos($file, $search) !== FALSE){
        echo 'name already used, choose another';
        header('Location: '.$_SERVER['PHP_SELF']);
     }
    fclose($handle);
  }
  if(isset($_POST['pwd'])){
     $password = $_POST['pwd'];
  }
  $text = $username . "," . $password . "\n";
  $fp = fopen("accounts.txt", 'a+') or die("Unable to open file!");
  if(fwrite($fp, $text)){
     echo "saved";
     fclose($fp);
     header("Location: commentWall.php");
  }
  else{
     echo "Unable to store credentials.";
     header('Location: '.$_SERVER['PHP_SELF']);
  }
} else {
?>
<html>
<body>
<h1>Please enter your information to create a new login account</h1>
 <form method="post">
  Login Name:<input type = "text"  name = "name" value = "" required><br/>
  Password:<input type = "password" name = "pwd" value = "" required><br/>
  <input type = "submit" name="submit_btn" id = "submit" value = "submit"/>
 </form>
</body>
</html>
<?php
}
?>

答案 1 :(得分:-1)

在检测到名称正在使用后,脚本不会停止。你需要这样做:

if (strpos($file, $search) !== FALSE) {
    header("Location: " . $_SERVER['PHP_SELF']);
    exit;
}

此外,如果您已经产生了输出,header()也不起作用。您应该将顶部的HTML块移动到else测试的if ($_POST)子句。