Download kotlin Programming APP on PlayStore
Download Website SEO Lessons APP on PlayStore
HTTP is a stateless protocol, meaning information is not cached between the various views of a visitor. This is, of course, impractical if we need to store certain information about a visitor, for example, which username he logged in with. To solve this, you use PHP sessions.
Technical background – PHP Session
Sessions give you the ability to capture specific data during a sequence of calls to your website. Each visitor is assigned a unique session ID, a possible session ID could look like this: dadafb244bbcb4bb84116d38f0ebd077, This session ID is re-sent to the web server by the visitor’s browser at each page view, allowing the web server to identify the visitor and load values from previous page views. The session ID is either appended to the URL as a GET parameter by the browser or stored locally in a cookie at the visitor’s site. Saving as a cookie is to be preferred for security reasons and is also preferred by PHP. Fortunately, as a web developer, you often do not have to worry about passing on the session ID, PHP actually takes all the work from there.
On the server then for each session ID locally a memory is set up, which can contain any variables for the visitor. For example, in the session, we can save for a visitor the username with which he logged in, which goods are in his shopping cart, etc.
The user has no way to see or manipulate the variables in his session. He only has the information as to which session ID was assigned to him by the web server.
Safety – PHP Session
Although sessions do not provide 100% security, they are still relatively secure. Each time the page is called, the browser informs the web server which session ID it has. Now, a malicious visitor can easily manipulate his session ID and could specify the session ID of another visitor. The thief could pretend to be someone else in a community.
How does the attacker get the PHP Session ID?
As mentioned above, session IDs are either passed via the URL using the parameter?PHPSESSID or stored as a cookie at the visitor. If the session IDs are transmitted via URL, then it may happen that the user copies this URL and, for example, sends it via e-mail or Facebook to friends and acquaintances. If the friends then call the link, they continue to use the session ID and are logged in with another account. This is especially problematic when posting the link on a public page.
If instead cookies are used, which is the default and happens to all visitors who have not explicitly disabled cookies, the attacker must reach this cookie to steal the session. This can be done, for example, by using a Trojan on the computer or by listening to the line.
Of course, the thief can guess a session ID, but this is very unlikely. It is more likely that the lottery draws the same numbers several times in a row than guessing a session ID by chance. That’s why we should not worry about that.
In summary, sessions are pretty secure and we usually do not have to worry about stealing a session ID. Very critical operations, such as the deletion of the account or the like, but should be backed up with an additional password query again.
Getting started – Register sessions
If we want to use sessions in a script before we make any output, we have to issue the command session_start(); call:
<?php
session_start();
?>
It is advisable to have this code always at the top of the scripts. If you get the message Can not send session cookie – headers already sent by, then there was an issue somewhere before session_start (). An empty line or even a space before <?Php already suffices.
If we want to store a value/variable across multiple page views in the session, then this is done as follows:
<?php
$_SESSION['name'] = "value";
?>
We can later output this value, also on other pages, as follows:
<?php
$name = $_SESSION['name'];
echo $name;
?>
Important, whenever you ‘re working with sessions somewhere, session_start () must have been run before. Try it out, saves in page1.php a value in a session and then give in page2.php this value again.
You can use the session variable like any other variable in PHP. You can store numbers, strings or even arrays in it.
Check if PHP session variable is registered
Often it is advisable to check whether a certain session variable has already been registered. This is done by means of the function isset($variable) :
<?Php
session_start();
if (!isset ($_SESSION ['visited'])) {
echo "You have not visited this page yet";
$ _SESSION['visited'] = true;
} else {
echo "You have already visited this page";
}
?>
Here it is first checked if the session variable already exists. If it does not exist, it will be registered.
If we just wrote isset instead of !Isset, we could check if the session was registered. This can be used for logins:
<? Php
session_start();
if (isset($_SESSION ['username'])) {
echo "Welcome".$_SESSION['username'];
} else {
echo "Please log in first";
}
?>
How to Delete PHP sessions
To delete all session data for the session use session_destroy():
<?php
session_destroy();
?>
This command deletes all data of the session and can be useful if the user eg wants to log out of your system. Remember, you must first run session_start() before you can run session_destroy().
To delete a single session variable you can unset ($variable) use:
<?php
unset($_SESSION['name']);
?>
This command deletes the values for the session variable name. Here is a small example:
<?Php
session_start();
if (isset($_SESSION['visited'])) {
echo "You visited the page before";
unset ($_SESSION['visited']);
} else {
echo "You have NOT visited the site before";
$_SESSION['visited'] = true;
}
?>
This script jumps back and forth between the two variants with each call.
Simple Registration/Login script with sessions php
To make the whole concept of sessions a bit more understandable, a small example follows. In a form the visitor will be able to enter his name, there will be an internal area with several pages and a page for the logout.
registeration_form.html
<form action="login.php" method="post">
Name: <br />
<input type="Text" name="name" />
<input type="Submit" />
</form>
login.php
<? Php
session_start(); //Do not forget
$name = $_POST['name'];
if(!isset($name) OR empty($name)) {
$name = "guest";
}
//register session
$ _SESSION ['username'] = $name;
// output text
echo "Hello $name <br />
<a href=\"page2.php\"> page 2 </a> <br />
<a href=\"logout.php\"> Logout </a> ";
?>
page2.php
<?Php
session_start(); //Very important
if (!isset($_SESSION['username'])) {
die("Please login first"); // Let's finish the rest of the script
}
// Store the value of the session in $name
$name = $_SESSION['username'];
// output text
echo "It's still called: $name
<a href=\"logout.php\"> Logout </a>";
?>
logout.php
<?php
session_start();
session_destroy();
echo "Logout successful";
?>
This is a very simple example, but it shows the strength of sessions right away. In the form we give our name, these data are then sent to login.php. There they will be queried and the name from the form will be saved in the session username. If we then click on the link and get to page2.php, we can continue to print the name of the visitor (the name from the form). This could be continued on any number of pages, with unlimited session variables.