2016-05-09 253 views
-1

我试图创建一个使用PHP的登录页面,我希望我的代码检查按下登录按钮后给出的用户名和密码。但即使未按下登录按钮,代码也会执行。我在网上搜索了几十个代码,几乎所有的代码都是以这种方式实现的,所以我不明白这里有什么问题。这里是我的代码:php isset不提交按钮

<HTML> 
    <HEAD> 
     <TITLE>Welcome to FoodOrder - Log In or Sign Up</TITLE> 

    </HEAD> 
    <BODY background = "foodOrder.png"> 

     <?php 
     session_start(); 
     $con = mysqli_connect("xxxx", "xxxx", "xxxx", "xxxx"); 

     if(mysqli_connect_errno()){ 
      echo "Failed to connect, please check your username and password: ".mysqli_connect_error(); 
     } 

     if(isset($_SESSION['user'])!= ""){ 
      header("Location: home.php"); 
     } 

     if(isset($_POST["login_button"])){ 
      $username = mysqli_real_escape_string($_POST['username']); 
      $password = mysqli_real_escape_string($_POST['password']); 
      $sql = "SELECT password from user where username = '$username'"; 
      $res = mysqli_query($con,$sql); 
      $row = mysqli_fetch_array($res); 
      if($row['password'] == md5($password)){ 
       $_SESSION['user'] = $username; 
       header("Location : home.php"); 
      } else { 
       ?> <script>alert('wrong username or password');</script> <?php 
      } 
     } 


     ?> 

     <center> 
      <div id ="login form"> 
       <form method = "POST"> 
        <table align = "center" width = "25%" border = "0"> 
         <tr> 
          <td><input type = "text" name = "username" placeholder = "your_username_here" required></td> 
         </tr> 
         <tr> 
          <td><input type = "text" name = "password" placeholder = "your_password_here"></td> 
         </tr> 
         <tr> 
          <td><input type = "submit" name = "login_button" value = "Log In" /></td> 
         </tr> 
         <tr> 
          <td><a href = "register.php">Sign Up</a></td> 
         </tr> 
        </table> 
       </form> 
      </div> 
     </center> 

    </BODY> 



</HTML> 
+3

我希望那些更换此

if(isset($_SESSION['user'])!= ""){ header("Location: home.php"); } 

是不是你真正的凭据..如果'登录in'不按哪个代码执行?你也不应该逃避那些不会去db的输入,这样一个带引号的密码就会被错误地散列。你也不应该使用'md5'作为密码。 – chris85

+2

尽管编辑,如果这些是您的凭据重置您的帐户。证书可能已经被破坏并且仍然存在于修订中。 – chris85

+0

@ chris85它正确地到达db,但它错误地保存在会话中。 – Rudie

回答

0

检查您的代码,删除md5一次。 $_SESSION VARIABLE无法正常工作。

也可以尝试这个

if(!$_SESSION['user']){ 
      header("Location: home.php"); 
     } 
+0

为什么你的isset里面有感叹号? 'isset(!$ _ SESSION ['user'])' –

+0

它将检查$ _SESSION变量是否有任何东西。 –

+0

很确定这是一个错误。 ** E_COMPILE_ERROR:type 64 - 不能对表达式的结果使用isset()(您可以使用“null!==表达式”)** –