简体   繁体   English

使用$ _SESSION存储日期并将其传输到另一个php文件

[英]Using $_SESSION to store date and transfer it to another php file

I have 2 PHP file and I use session in order to pass a variable(date format) to another PHP file. 我有2个PHP文件,并且我使用会话来将变量(日期格式)传递给另一个PHP文件。 This is the php files. 这是PHP文件。

main.php main.php

<!DOCTYPE html>
<html>

<?php
session_start();
$showDate = date("Y.m.d");
$_SESSION['storeDate'] = $showDate;
?>

<form action="insert.php" method="post">
<input type="submit" />
</form>

</body>
</html>

insert.php insert.php

<?php
session_start();
echo $_SESSION['storeDate'];

session_destroy()
?>

When I click on the submit button, the output should be the date ( $_SESSION['storeDate'] ) but I got an error instead: 当我单击提交按钮时,输出应为日期( $_SESSION['storeDate'] ),但出现错误:

Notice: Undefined index: storeDate. 注意:未定义的索引:storeDate。

How do I correct this so that it will display the the correct output. 我该如何纠正它,以便显示正确的输出。

put PHP code top of the page specially session_start(); 将PHP代码放在页面顶部,特别是session_start(); mentioned 提到

main.php main.php

<?php
    session_start();
    $showDate = date("Y.m.d");
    $_SESSION['storeDate'] = $showDate;
?>
<!DOCTYPE html>
<html>
<form action="insert.php" method="post">
<input type="submit" />
</form>

</body>
</html>

insert.php insert.php

<?php
session_start();
echo $_SESSION['storeDate'];

session_destroy()
?>

You are getting this error after refreshing or reloading the page. 刷新或重新加载页面后,您将收到此错误。 Because each time you refresh the page. 因为每次刷新页面。 you destroy your session by 你破坏了你的会议

session_destroy();

remove session_destroy(); 删除session_destroy();

and than refresh or reload it will work. 然后刷新或重新加载它就可以了。 or dont refresh or reload. 或不刷新或重新加载。

because each time when you reload your page. 因为每次您重新加载页面时。 you destroy the value in session. 您会破坏会话中的值。

I've tested your script and except the little structural mistakes you made, all seems working right. 我已经测试了您的脚本,除了您犯的一些小结构性错误之外,其他所有方法似乎都可以正常工作。 Corrected your index.php: 更正了index.php:

<?php
session_start();
$showDate = date("Y.m.d");
$_SESSION['storeDate'] = $showDate;
echo $_SESSION['storeDate'];
?>
<!DOCTYPE html>
<html>
    <head>
        <title>Test</title>
    </head>
    <body>
        <form action="insert.php" method="post">
            <input type="submit" />
        </form>
    </body>
</html>

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

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