Xampp 中的 PHP 会话问题 [英] Problem with PHP session in Xampp

查看:49
本文介绍了Xampp 中的 PHP 会话问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最简单的,如果 file_1.php 包含

At it's simplest, if file_1.php contains

<?php

  session_start(); 

  $_SESSION["test_message"] = "Hello, world";

  header("Location: http://localhost/file_2.php");
?>

和file_2.php包含

and file_2.php contains

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
</head>
<body>

<?php

  if (!(isset($_SESSION["test_message"])))
    echo "Test message is not set";
  else
    echo $_SESSION["test_message"];

var_dump($_SESSION);

  session_destroy();
?>

</body>
</html>

结果是 Test message is not set 并且 var_dump($_SESSION) 返回 null - 本地,使用 Xampp.但是,如果我将这些相同的文件上传到付费托管网站,它会起作用并且我看到

the result is Test message is not set and a var_dump($_SESSION) returns null - locally, with Xampp. However, if I upload those same files to a paid-for hosted web site, it works and I see

Hello, world
array
  'test_message' => string 'Hello, world' (length=12)

当我在 Xampp 下查看 PHPinfo 时,它显示 Session Support enabled.我做错了什么?

When I look at PHPinfo under Xampp it shows Session Support enabled. What am I doing wrong?

推荐答案

你忘记了 file_2.php 顶部的 session_start

You've forgotten the session_start at the top of file_2.php

所以应该是:

<?php
session_start(); 
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
</head>
<body>

<?php

  if (!(isset($_SESSION["test_message"])))
    echo "Test message is not set";
  else
    echo $_SESSION["test_message"];

var_dump($_SESSION);

  session_destroy();
?>

</body>
</html>

session_start() 应该位于您需要访问会话函数的每个文件的顶部.

session_start() should be at the top of every file where you need to access the session functions.

在重定向到另一个页面之前,您确实应该使用 session_write_close.

You should really use session_write_close before redirecting to another page.

第一个文件:

<?php
session_start(); 

$_SESSION["test_message"] = "Hello, world";

session_write_close(); 
header("Location: http://localhost/file_2.php");
?>

这篇关于Xampp 中的 PHP 会话问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆