A session is a way to keep details of an application when it is transferred from one page to another. PHP uses natively sessions
Session must be declared at the beginning of the page, using the function: session_start(); and we close the session with session_destroy();
Warning! If your php file is said to work with sessions beginning session_start () and session_destroy end of the file, then data from this session will not forward to another page.
The session_destroy() function is used only when we’re done with the session, eg to exit from an account.
Save the information sessions is a simple example:
$_SESSION["my_session"] = "Some text or anything else"; |
And finally let’s see a complete demo:
<?php session_start(); $_SESSION["my_session"] = "Some text or anything else"; echo $_SESSION["my_session"]; session_destroy(); ?> |
the above code will display the value of our session: Some text or anything else
Now we create two files named: page1.php and page2.php
In page1.php we place the following code:
<?php session_start(); $_SESSION["my_session"] = "Some text or anything else"; ?> |
and in page2.php we place:
<?php session_start(); echo $_SESSION['my_session']; ?> |
And if you go from page1.php to page2.php you will see the value of our session because we didn’t destroyed the sessionin the first page with session_destroy(); function.
Conclusion: With the help of php sessions we passed the variables from one page to another.
Note: For each file you want to use PHP sessions you must place in the top of page the session_start(); function so we can let know PHP what we want.
2 Comments
Pingback: Send form data once by Maribol Labs
Pingback: Using PHP cookies | Maribol Labs