Sessions and Forms in PHP
Let's say we have two PHP files. Let's place a form in the
file test1.php that asks
the user for two numbers:
<form method="GET">
<input name="num1">
<input name="num2">
<input type="submit">
</form>
In the same file, let's place the form processing code. In this code, we will write the input data to the session:
<?php
session_start();
if (!empty($_GET)) {
$_SESSION['num1'] = $_GET['num1'];
$_SESSION['num2'] = $_GET['num2'];
}
?>
An important nuance: in the file, the form processing code must be placed before the form itself. Why: because in this code we are working with the session, and therefore there should be no output to the screen before this.
Now let's find the
sum of the numbers stored in the session in the file test2.php:
<?php
if (!empty($_SESSION)) {
echo $_SESSION['num1'] + $_SESSION['num2'];
}
?>
In what sequence should this all
work? First, the user goes to
the page test1.php, fills out the form,
and clicks the button. After that, they land again
on test1.php, but now with the submitted
form data. At the same time, they enter the condition
in which we write the form data to the session.
Then the user must manually go to
the page test2.php - and there they will see
the sum of the entered numbers.
You might ask: why complicate things like this? After all,
the form could have been immediately sent to the page
test2.php. The thing is, that in this
case, the convenience lies in the fact that the form itself and the code
for its processing are located on the same page.
This, of course, is not always convenient, but sometimes
it is necessary.
On one page, using a form, ask the user for their last name, first name, and age. Write this data to the session. When accessing another page, display this data on the screen.