php 注意:未定义变量:第 9 行“”中的 _SESSION

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15594498/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 09:32:10  来源:igfitidea点击:

Notice: Undefined variable: _SESSION in "" on line 9

phperror-handling

提问by user2203600

Here is my php code:

这是我的php代码:

<?php include("inc/incfiles/header.inc.php")?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Member Index</title>
<link href="css/main.css" rel="stylesheet" type="text/css" />
</head>
<body>
<h1>Welcome <?php echo ($_SESSION['SESS_fname']);?></h1>
<a href="member-profile.php">My Profile</a> | <a href="logout.php">Logout</a>
<p>This is a password protected area only accessible to members. </p>
</body>
</html>

I know something I wrong with the code but I don't know how to fix it. My error says: "Notice: Undefined variable: _SESSION in C:\xampp\htdocs\Smasher\member-index.php on line 9"

我知道代码有问题,但我不知道如何解决。我的错误说:“注意:未定义变量:_SESSION in C:\xampp\htdocs\Smasher\member-index.php 第 9 行”

How can I fix the error so it will say the user's first name? The first name in the database table on mySQL is called fname.

如何修复错误以便它显示用户的名字?mySQL 上的数据库表中的第一个名称称为fname.

回答by Yassir Ennazk

Add

添加

session_start();

at the beginning of your page before any HTML

在任何 HTML 之前的页面开头

You will have something like :

你会有类似的东西:

<?php session_start();
include("inc/incfiles/header.inc.php")?>
<html>
<head>
<meta http-equiv="Content-Type" conte...

Don't forget to remove the space you have before

不要忘记删除您之前拥有的空间

回答by What have you tried

First, you'll need to add session_start()at the top of any page that you wish to use SESSIONvariables on.

首先,您需要在要session_start()在其上使用SESSION变量的任何页面的顶部添加。

Also, you should check to make sure the variable is set first before using it:

此外,您应该检查以确保在使用变量之前先设置变量:

if(isset($_SESSION['SESS_fname'])){
    echo $_SESSION['SESS_fname'];
}

Or, simply:

或者,简单地说:

echo (isset($_SESSION['SESS_fname']) ? $_SESSION['SESS_fname'] : "Visitor");