如果我使用 header() 函数,登录索引表单不适用于 login.php

Posted

技术标签:

【中文标题】如果我使用 header() 函数,登录索引表单不适用于 login.php【英文标题】:Login index form is not working with login.php if i use header() function 【发布时间】:2016-05-08 18:23:23 【问题描述】:

我是 php 的初学者。 我正在尝试制作一个登录表单(index1.php)。 如果我使用表单标签中的“action”属性将它重定向到 login.php,它工作正常。 但我也想对同一个索引表单进行一些验证。所以,我使用标头函数将其重定向到“login.php”,而不是“action”属性。

无论我是否输入正确的用户名和密码,在执行 login.php 的最后一个 else 时,它​​都会给我无效变量 '$username' 和 '$password' 的错误(//那个用户不存在) . 请帮助我了解我的代码有什么问题以及我应该怎么做才能让它与 login.php 一起运行?

这里是index1.php的代码

  <!DOCTYPE html>
<html>
<head><br>
<style>
.error color: #FF0000;
</style>
</head>
<body style="font-family: verdana, sans-serif;";>   
<hr />
<div style="width: 77%; height: 300px; padding: 30px; border: 5px solid #e3e3e3; background-color: #F8F8F8 ; color: #000; margin: 100px;" align="center">
 <br>
<?php

 $username=$password="";
 $Err="";

 if($_SERVER['REQUEST_METHOD']== "POST")
   

     $valid = true;

     if ((empty($_POST["username"])) || (empty($_POST["password"])))
    
      $Err = "Please Enter your username and password";
      $valid = false; 
    

   else 
    

      $username = test_input($_POST["username"]);
      $password = test_input($_POST["password"]);
    


   if($valid)
    
     header("location:login.php");
   


  

 function test_input($data) 

   $data = trim($data);
   $data = stripslashes($data);
   $data = htmlspecialchars($data);
   return $data;


?>

 <span class="error"><?php echo $Err; ?></span>
 <h2>Login</h2>
 <form action="menubar.php?page=index1" method="post">
      <font size="3">Username:<input type="text" name="username" style="padding: 4px;"/><p>
      Password: <input type="password" name="password" style="padding: 4px;"/><p>
                 <input type="submit" value="Login" style="padding: 4px; width: 5em; height: 1.9em;"/></font>
    </form>
     <h5> No Account?<a href="menubar.php?page=register">Register!</a></h5>
    </div>
</body>
</html>

这里是login.php的代码。

<?php

session_start();

$username=$_POST["username"];
$password=$_POST["password"];
$message[]="Fill up both username and password";

    $connect=mysql_connect("localhost","root","") or die("Couldnt connect to Database");
    mysql_select_db("login") or die("Couldnt find Database");
    $query = mysql_query("SELECT * FROM users WHERE username='$username'");

    $numrows = mysql_num_rows($query);

    if($numrows!==0)//username exists in database
    
        while($row = mysql_fetch_assoc($query))
        
            $dbusername = $row['username'];
            $dbpassword = $row['password'];
        
        if($username==$dbusername&&$password==$dbpassword)//valid username and password
        

            $_SESSION['username'] = $username;
           header("Location: menubar.php?page=home");
        
        else//incorrect password or username
        die("incorrect password or username");

    
    else//that user doesnt exit
    die("that user doesnt exit");//


?>

好的,现在我改用'sqli'

这是更新的 login.php 代码

<?php

session_start();

$username=$_POST["username"];
$password=$_POST["password"];
$message[]="Fill up both username and password";

    $connect=mysqli_connect("localhost","root","") or die("Couldnt connect to Database");
    mysqli_select_db($connect,'login') or die("Couldnt find Database");
    $query = mysqli_query("SELECT * FROM users WHERE username='$username'");

    $numrows = mysqli_num_rows($query);

    if($numrows!==0)//username exists in database
    
        while($row = mysqli_fetch_assoc($query))
        
            $dbusername = $row['username'];
            $dbpassword = $row['password'];
        
        if($username==$dbusername&&$password==$dbpassword)//valid username and password
        

            $_SESSION['username'] = $username;
           header("Location: menubar.php?page=home");
        
        else//incorrect password or username
        die("incorrect password or username");

    
    else//that user doesnt exit
    die("that user doesnt exit");//


?>

现在更新后我没有收到无效变量的错误。 但它仍然无法正常进行。无论我输入正确的用户名和密码,它都在执行最里面的 if 即(//有效的用户名和密码)

谢谢....

【问题讨论】:

还在使用 mysql_connect?为什么?你能在数据库中测试你的查询吗? 首先,您的代码中有几个主要问题:mysql_ 语法已过时且不安全:请改用pdo 或mysqli;那么没有散列的存储密码是非常不安全的:看看内置的password_hash。顺便说一句,您检查了一些错误吗?我认为问题出在 SQL 查询中,如果结果是“那个用户没有退出”。通过phpMyAdmin尝试查询是否正确。 感谢大家的回复,我在phpmyadmin中测试了查询,运行正常。我不明白为什么它显示无效变量的错误,即 $username 和 $password 好吧,正如你所说,我使用了'mysqli',但现在,无论我是否输入正确的用户名和密码,它都会执行最里面的 if 即(//有效的用户名和密码)。好消息是它不再给出无效变量的错误。 @Sachin 你能用你当前的代码更新你的帖子吗 【参考方案1】:

非常重要的是要注意,在设置标头之前,您应该没有向客户端发送任何输出-

header("Location: menubar.php?page=home");//or login.php

所以在发送任何数据之前验证您的数据并设置标题,如果无效数据则发送正常数据。

更新:下面是完整的测试代码

index1.php

<?php session_start();?>
<!DOCTYPE HTML>
<html>
<head><br>
<style>
    .error color: #FF0000;
</style>
</head>
<body style="font-family: verdana, sans-serif;";>   
<hr />
<div style="width: 77%; height: 300px; padding: 30px; border: 5px solid #e3e3e3; background-color: #F8F8F8 ; color: #000; margin: 100px;" align="center">
 <br>
 <?php if(isset($_SESSION['message'])) echo  "<span class='error'>".$_SESSION['message']."</span>"; $_SESSION['message']=null;?>
 <h2>Login</h2>
 <form action="login.php" method="post">
         <font size="3">Username:<input type="text" name="username" style="padding: 4px;"/><p>
  Password: <input type="password" name="password" style="padding: 4px;"/><p>
             <input type="submit" value="Login" style="padding: 4px; width: 5em; height: 1.9em;"/></font>
</form>
 <h5> No Account?<a href="menubar.php?page=register">Register!</a></h5>
</div>
</body>
</html>

登录.php

<?php

session_start();
$username=$password="";
$Err="";

if($_SERVER['REQUEST_METHOD']== "POST")
 
    $valid = true;
 if ((empty($_POST["username"])) || (empty($_POST["password"])))

  $Err = "Please Enter your username and password";
  $valid = false; 

else 


  $username = test_input($_POST["username"]);
  $password = test_input($_POST["password"]);

   if($valid) 
    $valid = false;//reset $valid value to validate for Database test

    //$username=$_POST["username"];
    //$password=$_POST["password"];
    //$message[]="Fill up both username and password";

    $connect=mysqli_connect("localhost","root","") or die("Couldnt connect to Database");
    mysqli_select_db($connect,'login') or die("Couldnt find Database");
//Note: mysqi_query() returns results of query
    $result = mysqli_query($connect, "SELECT * FROM users WHERE username='$username'");//update here pass the $connect parameter

    $numrows = mysqli_num_rows($result);//change here

if($numrows!==0)//username exists in database

    $dbusername = null;//move it up for visibility after while block
    $dbpassword = null;
    while($row = mysqli_fetch_assoc($result))//Note here pass the result
    
        $dbusername = $row['username'];
        $dbpassword = $row['password'];
    
    if($username == $dbusername&&$password==$dbpassword)//valid username and password
    

        $_SESSION['username'] = $username;
       header("Location: menubar.php?page=home");//the landing page
       die();
    
    else
        //incorrect password or username
        $Err = "incorrect password or username";
        $valid = false;
    


else 
    //that user doesnt exit
    $Err = "that user doesnt exit";
    $valid = false;
   
 //header("location:index.php");
   
if(!$valid) 
    $_SESSION['message'] = $Err;//Put the message in $_SESSION variable
    header("location:index1.php");

 
function test_input($data) 

   $data = trim($data);
   $data = stripslashes($data);
   $data = htmlspecialchars($data);
   return $data;

?>

menubar.php

<?php

session_start();

$page=isset($_GET["page"])?$_GET["page"]:"";
if(isset($page)) 
    header("location: ".$page.".php");
 else 
    header("location: 404.php");

?>

【讨论】:

大声笑我是菜鸟兄弟。我不明白你的意思。你用的高保真语言太多了。能否请您编写代码并告诉我需要替换哪一行?如果我实际使用它,我只能更好地理解它。谢谢 希望这有助于完成流程。 在上一个代码中,您从menubar.php 页面重定向到login.php,并尝试使用$_POST['username'] 访问login.php 中的数据。这是无效的。只有在客户端发送数据并且表单方法为post 时,您才能访问$_POST['username']。否则,如果数据是URL 的一部分,则必须使用$_GET['username']$_REQUEST['username'] 获取参数。示例:/login.php?username=Kamal&amp;password=kamal。我希望你明白这一点。 非常感谢兄弟,我试过你的代码,它也工作得很好。我真的非常感谢你们的努力。我今天学到了很多,因为你们。谢谢。【参考方案2】:

您的代码中的问题在于 login.php$_POST["username"]$_POST["password"] 从未设置过,因此您能做的最好的事情就是不要使用 header 而只使用 require_once

<!DOCTYPE HTML>
<html>
<head><br>
<style>
.error color: #FF0000;
</style>
</head>
<body style="font-family: verdana, sans-serif;";>   
<hr />
<div style="width: 77%; height: 300px; padding: 30px; border: 5px solid #e3e3e3; background-color: #F8F8F8 ; color: #000; margin: 100px;" align="center">
 <br>
<?php

 $username=$password="";
 $Err="";

 if($_SERVER['REQUEST_METHOD']== "POST")  

     $valid = true;

     if ((empty($_POST["username"])) || (empty($_POST["password"])))

      $Err = "Please Enter your username and password";
      $valid = false; 

    else

      $username = test_input($_POST["username"]);
      $password = test_input($_POST["password"]);

    


   if($valid)
    
     require_once('login.php');
   


 

 function test_input($data) 
   $data = trim($data);
   $data = stripslashes($data);
   $data = htmlspecialchars($data);
   return $data;


?>

 <span class="error"><?php echo $Err; ?></span>
 <h2>Login</h2>
 <form action="menubar.php?page=index1" method="post">
      <font size="3">Username:<input type="text" name="username" style="padding: 4px;"/><p>
      Password: <input type="password" name="password" style="padding: 4px;"/><p>
                 <input type="submit" value="Login" style="padding: 4px; width: 5em; height: 1.9em;"/></font>
    </form>
     <h5> No Account?<a href="menubar.php?page=register">Register!</a></h5>
    </div>
</body>
</html>

【讨论】:

非常感谢兄弟,我试过了,它工作正常。再次感谢.. 赞赏:)【参考方案3】:
    如前所述,将所有 PHP 代码放在任何 HTML 输出之前 您没有使用 header() 函数传递 POST 变量,您可以使用会话或 POST 到同一页面

所以你的代码应该是这样的

<?php

 $username=$password="";
 $Err="";

 if($_SERVER['REQUEST_METHOD']== "POST")
   

     $valid = true;

     if ((empty($_POST["username"])) || (empty($_POST["password"])))
    
      $Err = "Please Enter your username and password";
      $valid = false; 
    

   else 
    

      $username = test_input($_POST["username"]);
      $password = test_input($_POST["password"]);
    


   if($valid)
    
     include("login.php");
   


  

 function test_input($data) 

   $data = trim($data);
   $data = stripslashes($data);
   $data = htmlspecialchars($data);
   return $data;


?>

  <!DOCTYPE HTML>
<html>
<head><br>
<style>
.error color: #FF0000;
</style>
</head>
<body style="font-family: verdana, sans-serif;";>   
<hr />
<div style="width: 77%; height: 300px; padding: 30px; border: 5px solid #e3e3e3; background-color: #F8F8F8 ; color: #000; margin: 100px;" align="center">
 <br>

 <span class="error"><?php echo $Err; ?></span>
 <h2>Login</h2>
 <form action="menubar.php?page=index1" method="post">
      <font size="3">Username:<input type="text" name="username" style="padding: 4px;"/><p>
      Password: <input type="password" name="password" style="padding: 4px;"/><p>
                 <input type="submit" value="Login" style="padding: 4px; width: 5em; height: 1.9em;"/></font>
    </form>
     <h5> No Account?<a href="menubar.php?page=register">Register!</a></h5>
    </div>
</body>
</html>

【讨论】:

非常感谢,但我还不得不再次将“sqli”的更改恢复为“sql”。 sqli 给出了一些错误,但我认为我可以解决它们并使其也可以与 sqli 一起使用。谢谢你.. :) login.php 文件没有导致错误,因此即使不推荐使用 mysql 也不会导致问题。 是的,兄弟,您的代码运行良好。只是我不能勾选超过 1 个答案。我得到了超过 1 个答案,而且它们都工作得很好而且很简单。我感谢大家的帮助。谢谢 通常你选择最先出现的正确答案(并且在其他答案之后没有编辑)无论如何没关系,很高兴你解决了:)【参考方案4】:

那是因为你有一个输出:

?>
<?php

导致空行输出。

header() 必须在发送任何实际输出之前调用,无论是通过普通 HTML 标记、文件中的空白行还是通过 PHP

合并所有 PHP 代码并确保文件开头没有任何空格。

如果您有任何其他脚本,请在header('location: index.php'); 之后添加exit();

还要在最后一个 if 之后移动重定向标头。

【讨论】:

你可以使用 obstart();before header();

以上是关于如果我使用 header() 函数,登录索引表单不适用于 login.php的主要内容,如果未能解决你的问题,请参考以下文章

“header()” php 函数是不是取消设置全局变量?

如何在 POST 表单上设置 Header 字段?

pandas使用read_csv函数读取csv数据header参数指定作为列索引的行索引列表形成复合(多层)列索引使用方括号[]基于最外层列索引名称索引列数据

如果 REQUIRE_ONCE 存在,HEADER 命令不起作用[重复]

使用 php 和 ajax 进行登录表单验证

pandas读取csv数据header参数指定作为列索引的行索引列表形成复合(多层)列索引使用xs函数获取行切面数据(level参数指定行层索引列表key参数指定索引值列表)