Dear friends,
I want to transfer data from one page to other via SESSION variables my code of session1.php page is below

<!DOCTYPE html>

<html>

<head>
  <title>Hello!</title>
</head>

<body>
<form action="session2.php" method="post">
<input type="text" name="text" />
<input type="submit" name="submit" />
</form>
<?php

session_start();
$text=$_POST['text'];
$_SESSION['stext']=$text;
echo("session is set");

?>

</body>
</html>

and second code of session2.php

<!DOCTYPE html>

<html>

<head>
  <title>Hello!</title>
</head>

<body>

<?php
session_start();
if(isset($_POST['submit'])){

echo ":". $_SESSION['stext'];

}
?>

</body>
</html>

i got error
Notice: Undefined index: text in C:\wamp\www\Exercises\session1.php on line 16
please, guide me.

<?php
session_start();

must be the at the very top of youre script.
no html before it, not even a white-line;

for actual error message:
if just you run session1.php, $_POST will be empty.
test: var_dump($_POST);
the $_POST is filled bij the form only after you submit it
but action="session2.php" will redect to session2.php
so in session2.php $_POST['text'] will have the value input in the form.
So no need for $_SESSION.

@pzuurveen sorry, I didn't saw your reply! ;D

@zebnoon1

There are few errors: session_start() must be placed in top of both files. Then, you're submitting the form to session2.php, so the code between lines 14 and 21 of session1.php file will not work: because it runs when you open the page, i.e. before you submit the form.

In order to work: change session2.php to save the value in session and then redirect back to session1.php, in this file check if the session is set and if yes, then display the value. Example:

<?php

session_start();

?>
<!DOCTYPE html>
<html>
<head>
    <title>Session 1</title>
</head>
<body>

    <form action="session2.php" method="post">
        <input type="text" name="text" />
        <input type="submit" name="submit" />
    </form>

    <?php

        # does the session key exists?
        if(array_key_exists('stext', $_SESSION))
        {
            echo $_SESSION['stext'];

            # to delete
            # unset($_SESSION['stext']);
        }

    ?>

</body>
</html>

In session2.php:

<?php

    session_start();

    if(array_key_exists('text', $_POST))
    {
        $_SESSION['stext'] = $_POST['text'];
    }

    # redirect back
    header('Location: ./session1.php');
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.