简体   繁体   中英

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. This is the php files.

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

<?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:

Notice: Undefined index: 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(); mentioned

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

<?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();

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:

<?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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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