Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

How to work with Sessions in PHP

In this article we will learn how to work with sessions in PHP. We will see some functions and also how to create a login application using session.

A web session is very similar to a PC session, which to start, we have to put username and password, so your computer can know who is using the machine and store records safely. On a web site or system, the session is important when one wants more security on the page or when you want to have a user control. Also some programmers are used to store information of this resource and you can also set up a shopping cart from a e-commerce, as well will be storing the items or products and only in the end is that the dice are thrown in stock data.

Session in PHP consists of a way to preserve certain data across subsequent accesses. This enables you to build more customized applications and increase the appeal of your web site.

Note: "A PHP session variable is used to store information about, or change system settings or website to a user session. Session variables store information about a single user and are available to all pages in one application. "

Below we can see some session functions:

  • session_cache_expire - Return current cache expire
  • session_cache_limiter - Get and/or set the current cache limiter
  • session_commit - Alias of session_write_close
  • session_decode - Decodes session data from a session encoded string
  • session_destroy - Destroys all data registered to a session
  • session_encode - Encodes the current session data as a session encoded string
  • session_get_cookie_params - Get the session cookie parameters
  • session_id - Get and/or set the current session id
  • session_is_registered - Find out whether a global variable is registered in a session
  • session_module_name - Get and/or set the current session module
  • session_name - Get and/or set the current session name
  • session_regenerate_id - Update the current session id with a newly generated one
  • session_register_shutdown - Session shutdown function
  • session_register - Register one or more global variables with the current session
  • session_save_path - Get and/or set the current session save path
  • session_set_cookie_params - Set the session cookie parameters
  • session_set_save_handler - Sets user-level session storage functions
  • session_start - Start new or resume existing session
  • session_status - Returns the current session status
  • session_unregister - Unregister a global variable from the current session
  • session_unset - Free all session variables
  • session_write_close - Write session data and end session

Now let's have an overview of our login section.

In Figure 1 we see the operating logic of the session which we will create.

operation logic of the session

Figure 1: Operation logic of the session

The main page of a website or web system is commonly called the index. In our example we have an online system that when accessed the first thing he shows to the user is the login area, that can only access the web content system registered users who pass by the login. So in our index.php page we will create a login form.

Now we will start to develop our example, but first of all the reader has to be with the following requirements on your machine (based requirements in our example).

A database installed with at least one table:

  • DATABASE NAME: SERVER;
  • NAME OF THE TABLE: USER;

With the following fields:

  • ID_USER type and size 4 INT marked Primare key and auto increment;
  • NAME type VACHAR size 50;
  • PASSWORD type VACHAR size 50.

In the article we used the program EasyPHP 12.1, which now simulates a local server and comes with PhpMyAdmin.

Once installed EasyPHP and created the database with the necessary table and its fields, let's create our first page, which will be index.php. In Listing 1 we see the source code.

Listing 1: Source code from index.php

<html>
<head>
    <title>Working with Sessions in PHP - MrBool Tutorial</title>
</head>
<body>

<form method="post" action="controller.php" id="formlogin" name="formlogin" >
    <fieldset id="fie">
        <legend>LOGIN</legend><br />
            <label>Username : </label>

        <input type="text" name="username" id="username"  /><br />
            <label>Password :</label>
                <input type="password" name="password" id="password" /><br />
                <input type="submit" value="Login" />
    </fieldset>
</form>

</body>
</html>
 

Note: Remember that in this article we focus on how to create a login system working with session, not be concerned with the visual (CSS, jQuery), it is the responsibility of the reader.

We can see the result of listing 1 in the figure 2.

Result of listing 1

Figure 2: Result of listing 1

Now let's create the page "ope.php" which will have some functions as we can see in the listing 2.

This page will first receive data from the index.php page, connects to the database to research and soon after will decide if the user can access the system.

Listing 2: Source code of controller.php page

<?php
session_start();

$username = $_POST['username'];
$password = $_POST['password'];

$con = mysql_connect("127.0.0.1", "root", "Insert your database password here") or die ("Connection failed with the server");
$select = mysql_select_db("server") or die("No access to database, please contact the system administrator.");
 

$resut = mysql_query("SELECT * FROM `USER` WHERE `NAME` = '$username' AND `PASSWORD=` '$password'");

if(mysql_num_rows ($result) > 0 )
{
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
header('location:system.php');
}
else{
    unset ($_SESSION['login']);
    unset ($_SESSION['senha']);
    header('location:index.php');
     
    }
 
?>

Ok, now that we have a login page (index.php) and the page that receives the data and checks in the database if the user is registered or not (controller.php), we will create the main page (sytem.php), so that if the user is registered in the database, he will be redirected to it. Note that the responsibility to pass or not to MasterPage your system (system.php), will be the "controller.php."

We will now create a page with content from your system and give more emphasis on the header of the page, because over there we will put some security codes that we will explain more soon.

We can see the code in listing 3.

Listing 3: Source code of system.php page

<?php session_start(); ?>
<html>
<head>
	<title>Working with Sessions in PHP - MrBool Tutorial</title>
<?php 

if((!isset ($_SESSION['username']) == true) and (!isset ($_SESSION['password']) == true))
{
    unset($_SESSION['username']);
    unset($_SESSION['password']);
    header('location:index.php');
    }
 
$logged = $_SESSION['username'];

?>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />


</head>
<body>

	<table width="800" height="748" border="1">
  <tr>
    <td height="90" colspan="2" bgcolor="#CCCCCC">MrBool WebSystem

    <?php
    echo "Welcome".$logged."to the MrBool WebSystem";
    ?>
    </td>
  </tr>
  <tr>
    <td width="103" height="410" bgcolor="#CCCCCC">Navbar here</td>
    <td width="546">Content and icons here</td>
  </tr>
  <tr>
    <td colspan="2" bgcolor="#000000"> </td>
  </tr>
</table>

</body>
</html>

The code in the header checks if the session exists, because the user can simply do the username and type in the address bar of your browser the url for the site's main page (system), thereby bypassing the requirement to make a login. With this if it is not logged, the session will not be created, then to verify that the session does not exist the system will redirects to index.php.

After we logged at the system we will see the page system.php as we can see in the figure 3.

Logged page

Figure 3: Logged page

Another Example

Now we will see another way to use sessions in PHP.

As seen previously, to start a session, use the session_start() function.

For correct operation, it can not be after any OUTPUT data (echo, print, HTML, etc.).. It is recommended that the first line of code. If we want, we can also use a name to identify the session. In the example below, I will use MrBoolExample as name:

Listing 4: Starting session

<?php
session_start("MrBoolExample");
?>

Now, let's define the variables of a session. These should always be below the session_start(). The syntax is to set $ _SESSION['variable'].

Listing 5: Defining variables

<?php
session_start("MrBoolExample");
$_SESSION["name"] = "Using sessions in PHP";
$_SESSION["reading"] = "yes";
?>

We assume that the sessions identified the name of the article and you're reading it. Following the example, let's see if you're even reading:

Listing 6: Verifying the session

<?php
session_start("MrBoolExample"); 
	if($_SESSION["reading"]!=="yes"){
	//if $_SESSION["reading"] isn't "yes", the message below will show.
		echo "You aren't reading the article!";
	}else{
		//if yes, the message below will show.
		echo "You are reading the article ".$_SESSION["name"]." Thanks!";
}
?>

A session always remains active while the user is browsing. It is automatically destroyed when it closes the browser. But there is a way to destroy the session yourself, is using an authentication system, would be a kind of LOGOFF. For this, use the function session_destroy(), which should be after session_start().

Listing 7: Session destroy

<?php
session_start("MrBoolExample");
session_destroy();
echo "Session destroyed";
?>

If you want to leave just a blank variable, you can do using the unset() function.

Listing 8: unset() function

<?php
session_start("MrBoolExample");
unset($_SESSION["reading"]);
//this will erase only the variable "reading" of the active session. Others remain.
?>

Conclusion

After that, take the test on your machine. Do not forget that in this article we are concerned only with the operating logic of a session, so you can familiarize yourself with the environment, so do not worry about the visual part of the pages.

I hope you enjoyed the article, any questions just use the comments area at the end of this article.

If you have any article suggest, please make it for me by e-mail at ricoarrigoni@gmail.com, see you next time.



Front-end developer, WebEditor of MrBool.com and SEO Analyst. Work in the development area for over 4 years. For freelance work visit my portfolio: www.ricardoarrigoni.com.br

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login