注意:未定义的变量:username


Notice: Undefined variable: username

我的问题=当我试图在editor.php中使用$username时,为什么没有为它分配值

我有一个有效的登录系统。一旦用户登录,我想创建一个欢迎行,上面写着"欢迎[在此处插入用户名]"。目前,我在获取echo以检索变量"$username"时遇到了问题,因为我收到了以下错误:

注意:第60行editor.php中的未定义变量:username。

这是editor.php中的第60行。注意,editor.php是用户成功登录后指向的页面

<h4>Welcome <?php  echo $username;?> , to the editor.</h4>

$username变量在loginAuth.php中声明,当用户在login.php上提交他/她的登录详细信息时,就会运行该变量。

以下是loginAuth.php的相关代码:

<?php
error_reporting(E_ALL);  
ini_set('display_errors', 1); 
//Connect to DB
include_once dirname(__FILE__).'/db_connect.php';
// PHP >= 5.3
include_once __DIR__.'/db_connect.php';

//starts session
session_start();
if (isset($_POST['loginSub'])) {
//Variables declaration
$username = $_POST['user'];
$password = $_POST['password'];
//if username doesnt not equal empty space and password does not equal empty  
space, then...
if(trim($username) != '' and trim($password) != ''){
//Sanitizes whatever is entered 
$username=stripslashes($username);
$password=stripslashes($password);
$username=strip_tags($_POST['user']);
$password=strip_tags($_POST['password']);

$username=mysqli_real_escape_string($conn,$username);
$password=mysqli_real_escape_string($conn,$password);
//SQL query 
$query = mysqli_query($conn, "SELECT * FROM users WHERE user='$username' AND 
password = '$password' ")or die(mysqli_error($conn));
//applies msqli_num_rows to the $query. Counts how many rows 
$numrows=mysqli_num_rows($query);
//if there is a row that matches what has been entered in form, then...
if($numrows > 0){
//initialize session
$_SESSION['login_user']= $username; 
//take them to editor.php   
header("location: editor.php"); // Redirecting To Other Page
exit;
}else{
     echo "Username or password is incorrect.";
    }
}else{  
    echo "Please enter information";
}
}
?>

因此,基本上,editor.php页面由于某种原因无法获得$username var,因为它显然没有价值。。。即使我的登录页面成功工作。

根据请求,我在login.php中的HTML FORM:

 <form id="login" method="POST" action="loginAuth.php">
                    <label for="user"><strong>Login:</strong></label>
                    <input type="text"size=20 autocorrect=off autocapitalize=words name="user">
                    <label for="password" > <strong>Password:</strong></label> 
                    <input type="password" name="password">
                    <input name="loginSub" type="submit" value="Login"> 
                </form>  

以下是我研究过的其他问题,但未能应用于我自己的问题:

参考-这个错误在PHP中意味着什么?

PHP:";注意:未定义变量"注意:未定义索引";,以及";注意:未定义的偏移量";

您的变量在editor.php 中不存在

你需要从你的$_SESSION这样得到:

editor.php

<?php
$username = $_SESSION['login_user'];
....
<h4>Welcome <?php  echo $username;?> , to the editor.</h4>

当用户直接访问单个.php文件时,它们是完全独立的,就像重定向它们时一样。

由于将用户重定向到editor.php,因此在login中设置的变量$username不存在。这是一个不同的处理请求的过程。

editor.php需要以某种形式处理用户登录,您可能需要查看PHP会话处理。

//initialize session
$_SESSION['login_user']= $username; 

您将用户名存储在一个会话变量中,在这里;一种选择是在editor.php中镜像此操作,方法是执行。。。

$username = $_SESSION['login_user'];