如何在登录另一个web应用程序时使用PHP获取会话变量


How to get a session variable using PHP while login in another web application?

我是PHP新手。我想显示会话变量,如会话id,用户名,团队名称等从web应用程序。我的场景是我在一个独立的web应用程序登录。我使用php代码来显示我的会话变量,而在该web应用程序登录。

我的代码在这里

<?php
session_start();
?>
<?php
print_r($_SESSION);
?>

但是显示会话数据失败。我的代码输出是一个空白数组。

谁能帮我如何获得会话数据?

您没有在任何地方设置session值

<?php
session_start();
$_SESSION['username'] = 'logged_username';
$_SESSION['id'] = '007';
print_r($_SESSION);
?>

启动PHP会话

<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
echo "Session variables are set.";
?>
</body>
</html>

然后使用

<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
print_r($_SESSION);
?>
</body>
</html>

W3School示例

要使用会话数据,首先需要在会话

中存储一些数据
<?php
session_start(); // start your session its better you start your session in configuration file 
// create some global variables using session
$_SESSION['user_name'] = "Your Name";
$_SESSION['team_name'] = "Your Team Name";
?>

使用会话

echo $_SESSION['user_name']
// output - Your Name

check session ref - session in php

首先,您必须在使用session_start()函数的php应用程序的第一个开始会话。然后像这样用键设置会话变量

$_SESSION['user'] = $user

以相同的方式访问这些变量。

print_r($_SESSION['user'])
在访问其他文件时不要忘记启动会话。