简体   繁体   English

PHP会话不存储值

[英]PHP session not storing values

First page abc.html 第一页abc.html

< form action="xyz.php" method="post" >
< input type=text value="ABC" name="first" id="first" />
< /form>

Second page xyz.php 第二页xyz.php

session_start();

$var1 = $_Request['first'];
$_Session['myvar'] = $var1;
session_write_close();

echo "<a href='lkj.php'>click here</a>"

third page lkj.php 第三页lkj.php

session_start();

echo $_Session['var1'];

and the output comes nothing, its totally blank as there was nothing stored in the session variable. 并且输出什么也没有,它完全空白,因为会话变量中没有存储任何内容。
Can you please help me out with this? 你能帮我这个忙吗?

Your case is incorrect, and variable identifiers are case sensitive in PHP: 您的大小写不正确,并且变量标识符在PHP中区分大小写:

// Incorrect:
$var1 = $_Request['first'];
$_Session['myvar'] = $var1;
session_write_close();

// Should be:
$var1 = $_REQUEST['first'];
$_SESSION['myvar'] = $var1;
session_write_close();


// On lkj.php:
session_start();
echo $_SESSION['var1'];

Also, instead of using $_REQUEST I highly recommend using $_POST . 另外,我强烈建议您不要使用$_REQUEST ,而应使用$_POST Your form specifies method='post' . 您的表单指定method='post'

$var1 = $_POST['first'];
$_SESSION['myvar'] = $var1;

There are a few issues that I'm seeing with the code you provided. 我所提供的代码存在一些问题。

  1. You are referencing your variables incorrectly. 您错误地引用了变量。 On xyz.php you are setting $_Session['myvar'] = $var1; xyz.php您设置$_Session['myvar'] = $var1; and then on ljk.php you are trying to echo $_Session['var1'] which wouldn't exist, as it has not been set. 然后在ljk.php上尝试回显$_Session['var1'] ,该名称将不存在,因为尚未设置。 The variable that you would want to access would be $_SESSION['myvar'] , as that was the variable that was set in xyz.php . 您要访问的变量是$_SESSION['myvar'] ,因为那是在xyz.php中设置的变量。

  2. You want to utilize $_SESSION , not $_Session . 您要使用$_SESSION而不是$_Session

  3. You are using $_REQUEST which is a superglobal and can raise some security concerns. 您正在使用$_REQUEST ,它是一个超全局变量,可能会引起一些安全问题。 While your code may not be affected for its current purpose, its always a better idea to just avoid it. 尽管您的代码可能不会因为当前的目的而受到影响,但是避免它始终是一个更好的主意。 Instead utilize $_POST as that will only take the data that has been posted. 而是使用$_POST因为那样只会获取已发布的数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM