2017-06-18 132 views
-1

我正在尝试使用PHP进行登录会话,并收到并在我的数据库的“用户名”字段发生错误。 我的源代码是在这里:PHP注意:未定义的索引:用户名

的index.php

<?php 
session_start(); 
if(isset($_POST['bttLogin'])){ 
    require 'connect.php'; 
    $username = $_POST['username']; 
    $password = $_POST['password']; 
    $result = mysqli_query($con, 'SELECT * FROM account WHERE username=" '.$username.' " AND password="'.$password.' " '); 
    if (mysqli_num_rows($result)==1){ 
     $_SESSION['username'] = $username; 
     header('Location: welcome.php'); 
    } 
    else 
     echo "Account invalid"; 
} 
if(isset($_POST['username'])){ 
    $filename = $_POST['username']; 
} 

if (isset($_GET['logout'])){ 
    session_unregister('username'); 
} 

?> 
<form method="post"> 

    <table cellpadding="2" cellspacing="2" border="0"> 
     <tr> 
      <td> Username </td> 
      <td><input type = "text" name="usermame"></td> 
     </tr> 

     <tr> 
      <td> Password </td> 
      <td><input type = "password" name="password"></td> 
     </tr> 

     <tr> 
      <td> </td> 
      <td><input type = "submit" name="bttLogin" value="Login"></td> 
     </tr> 
    </table> 
</form> 

我做了我和我的数据库连接,但它口口声声说用户名是不确定的。请帮忙。

+0

你能告诉我们你的帐户表结构和你得到 – Dale

+1

你的脚本是[** SQL注入攻击的危险性错误**](https://stackoverflow.com/q/60174/5914775)。看看[Little Bobby Tables]发生了什么事(http://bobby-tables.com/)。改用[准备好的参数化语句](https://php.net/manual/en/mysqli.quickstart.prepared-statements.php)。 –

+1

**不要存储纯文本密码!** PHP提供['password_hash()'](https://php.net/manual/en/function.password-hash.php)和['password_verify()']( https://php.net/manual/en/function.password-verify.php)请使用它们。如果您使用的是5.5以前的PHP版本[这里有一个兼容包](https://github.com/ircmaxell/password_compat)。确保你[**不要转义密码**](https://stackoverflow.com/q/36628418/5914775)或在哈希之前使用其他任何清理机制。这样做会更改密码并导致不必要的附加编码。 –

回答

0

似乎你只是没有索引'用户名'在$ _SESSION变种。 你需要检查并在必要时对其进行初始化 - 这样的事情:

if (!isset($_SESSION['username'])) { 
    if (!is_array($_SESSION)) { 
     $_SESSION = []; 
    } 
    $_SESSION['username'] = $username; 
}