What is SESSION in PHP?

What is SESSION in PHP?

PHP is probably the most popular scripting language on the web. It is used to enhance web pages. With PHP, you can do things like create username and password login pages, check details from a form, create forums, picture galleries, surveys, and a whole lot more. If you’ve come across a web page that ends in PHP, then the author has written some programming code to liven up the plain, old HTML.

PHP is known as a server-sided language. That’s because the PHP doesn’t get executed on your computer, but on the computer you requested the page from. The results are then handed over to you, and displayed in your browser. Other scripting languages you may have heard of are ASP, Python and Perl. (You don’t need to know any of these to make a start on PHP. In fact, these tutorials assume that you have no programming experience at all.)

The most popular explanation of just what PHP stands for is “Hypertext Pre-processor”. But that would make it HPP, surely? An alternative explanation is that the initials come from the earliest version of the program, which was called Personal Home Page Tools. At least you get the letters “PHP” in the right order!

But PHP is so popular that if you’re looking for a career in the web design/web scripting industry then you just have to know it! In these tutorials, we’ll get you up and running. And, hopefully, it will be a lot easier than you think.

Working in PHP

The best way to explain how PHP works is by comparing it with standard HTML. Imagine you type the address of an HTML document (mysite.com/page.htm) in the address line of the browser. This way you request an HTML page. It could be illustrated like this:

how php works

As you can see, the server simply sends an HTML file to the client. But if you instead type mysite.com/page.php – and thus request an PHP page – the server is put to work:

The server first reads the PHP file carefully to see if there are any tasks that need to be executed. Only when the server has done what it is supposed to do, the result is then sent to the client. It is important to understand that the client only sees the result of the server’s work, not the actual instructions.

This means that if you click “view source” on a PHP page, you do not see the PHP codes – only basic HTML tags. Therefore, you cannot see how a PHP page is made by using “view source”. You have to learn PHP in other ways, for example, by reading this tutorial.

Uses of PHP

Anything. PHP is mainly focused on server-side scripting, so you can do anything any other CGI program can do, such as collect form data, generate dynamic page content, or send and receive cookies. But PHP can do much more.

There are three main areas where PHP scripts are used.

Server-side Scripting

This is the most traditional and main target field for PHP. You need three things to make this work. The PHP parser (CGI or server module), a web server and a web browser. You need to run the web server, with a connected PHP installation. You can access the PHP program output with a web browser, viewing the PHP page through the server. All these can run on your home machine if you are just experimenting with PHP programming. See the installation instructions section for more information.

Command Line Scripting

You can make a PHP script to run it without any server or browser. You only need the PHP parser to use it this way. This type of usage is ideal for scripts regularly executed using cron (on *nix or Linux) or Task Scheduler (on Windows). These scripts can also be used for simple text processing tasks. See the section about Command line usage of PHP for more information.

Writing Desktop Applications

PHP is probably not the very best language to create a desktop application with a graphical user interface, but if you know PHP very well, and would like to use some advanced PHP features in your client-side applications you can also use PHP-GTK to write such programs. You also have the ability to write cross-platform applications this way. PHP-GTK is an extension to PHP, not available in the main distribution. If you are interested in PHP-GTK, visit » its own website.

What you require to work with PHP

You need an editor to work with PHP

To start woking in PHP you need editor like Adobe DreamWeaver, Notepad++, Sublime Text etc.

A Server

Before you can write and test your PHP scripts, there’s one thing you’ll need – a server! Fortunately, you don’t need to go out and buy one. In fact, you won’t be spending any extra money. That’s why PHP is so popular! But because PHP is a server-sided scripting language, you either have to get some web space with a hosting company that supports PHP, or make your computer pretend that it has a server installed. This is because PHP is not run on your PC – it’s executed on the server. The results are then sent back to the client PC (your computer). 

You click on the given link to read about “how to install wampserver on windows“.

Wampserver is a software which allows you to test your PHP scripts on your own computer. It installs everything you need,

Practical of PHP

Basic Syntax of PHP

The PHP script is executed on the server, and the plain HTML result is sent back to the browser.

A PHP script can be placed anywhere in the document.

A PHP script starts with <?PHP and ends with ?>:

Example:

<?PHP // PHP code goes here ?>

The default file extension for PHP files is “.PHP”.

A PHP file normally contains HTML tags, and some PHP scripting code.

Below, we have an example of a simple PHP file, with a PHP script that uses a built-in PHP function “echo” to output the text “Hello World!” on a web page:

Example:

<!DOCTYPE html>
<html>
<body>
<h1>My first PHP page</h1>
<?PHP
echo "Hello World!";
?>
</body>
</html>

Output:

My first PHP page
Hello World!

PHP Variables

Variables are “containers” for storing information

As with algebra, PHP variables can be used to hold values (x=5) or expressions (z=x+y).

A variable can have a short name (like x and y) or a more descriptive name (age, carname, total_volume).

Rules for PHP variables

  • A variable starts with the $ sign, followed by the name of the variable
  • A variable name must start with a letter or the underscore character
  • A variable name cannot start with a number
  • A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
  • Variable names are case sensitive ($y and $Y are two different variables)

PHP Global Variables – Superglobals

Several predefined variables in PHP are “superglobals”, which means that they are always accessible, regardless of scope – and you can access them from any function, class or file without having to do anything special.

The PHP superglobal variables are:

  1. $GLOBALS
  2. $_SERVER
  3. $_REQUEST
  4. $_POST
  5. $_GET
  6. $_FILES
  7. $_ENV
  8. $_COOKIE
  9. $_SESSION

Explaining $_SESSION

Sessions in PHP

A PHP session variable is used to store information about, or change settings for a user session. Session variables hold information about one single user, and are available to all pages in one application. An alternative way to make data accessible across the various pages of an entire website is to use a PHP Session.

A session creates a file in a temporary directory on the server where registered session variables and their values are stored. This data will be available to all pages on the site during that visit.

PHP Session Variables

When you are working with an application, you open it, do some changes and then you close it. This is much like a Session. The computer knows who you are. It knows when you start the application and when you end. But on the internet there is one problem: the web server does not know who you are and what you do because the HTTP address doesn’t maintain state.

A PHP session solves this problem by allowing you to store user information on the server for later use (i.e. username, shopping items, etc). However, session information is temporary and will be deleted after the user has left the website. If you need a permanent storage you may want to store the data in a database.

Sessions work by creating a unique id (UID) for each visitor and store variables based on this UID. The UID is either stored in a cookie or is propagated in the URL.

Starting a PHP Session

Before you can store user information in your PHP session, you must first start up the session.

A PHP session is easily started by making a call to the session_start() function.This function first checks if a session is already started and if none is started then it starts one. It is recommended to put the call to session_start() at the beginning of the page.

Session variables are stored in associative array called $_SESSION[]. These variables can be accessed during lifetime of a session.

The following example starts a session then register a variable called counter that is incremented each time the page is visited during the session.

Make use of isset() function to check if session variable is already set or not.

Put this code in a test.PHP file and load this file many times to see the result:

Example:

<?PHP session_start(); ?>
<html>
<body>
</body>
</html>

The code above will register the user’s session with the server, allow you to start saving user information, and assign a UID for that user’s session.

Storing a Session Variable

The correct way to store and retrieve session variables is to use the PHP $_SESSION variable:

<?PHP session_start(); // store session data $_SESSION['views']=1; ?>
<html>
<body>
<?PHP //retrieve session data echo "Pageviews=". $_SESSION['views']; ?>
</body>
</html>

Output:

Pageviews=1

In the example below, we create a simple page-views counter. The isset() function checks if the “views” variable has already been set. If “views” has been set, we can increment our counter. If “views” doesn’t exist, we create a “views” variable, and set it to 1:

<?PHP
session_start();
if(isset($_SESSION['views']))
$_SESSION['views']=$_SESSION['views']+1;
else
$_SESSION['views']=1;
echo "Views=". $_SESSION['views'];
?>

Destroying a Session

If you wish to delete some session data, you can use the unset() or the session_destroy() function.

The unset() function is used to free the specified session variable:

<?PHP
session_start();
if(isset($_SESSION['views']))
  unset($_SESSION['views']);
?>

You can also completely destroy the session by calling the session_destroy() function:

<?PHP
session_destroy();
?>

Turning on Auto Session

You don’t need to call start_session() function to start a session when a user visits your site if you can set session.auto_start variable to 1 in PHP.ini file.

Sessions without Cookies

There may be a case when a user does not allow to store cookies on their machine. So there is another method to send session ID to the browser.

Alternatively, you can use the constant SID which is defined if the session started. If the client did not send an appropriate session cookie, it has the form session_name=session_id. Otherwise, it expands to an empty string. Thus, you can embed it unconditionally into URLs.

The following example demonstrates how to register a variable, and how to link correctly to another page using SID.

<?PHP
   session_start();
   if (isset($_SESSION['counter'])) {
      $_SESSION['counter'] = 1;
   } else {
      $_SESSION['counter']++;
   }
?>   
   $msg = "You have visited this page ".  $_SESSION['counter'];
   $msg .= "in this session.";
   echo ( $msg );
<p>
To continue  click following link <br />
<a  href="nextpage.PHP?<?PHP echo htmlspecialchars(SID); >">

The htmlspecialchars() may be used when printing the SID in order to prevent XSS related attacks.

PHP: Simple Password Protection with Session Timeout

The following PHP code is for creating a simple password protected page with a timeout session. It is an insecure primitive method for non-sensitive data, but useful nonetheless.

However, to improve security, the password is hashed and the protected content cannot be retrieved by a direct web link.

password protection in php
password security in php
password security in php

Simple PHP Password Protection

Directory Structure

WEBSERVER
  |
  |–/localstorage
  |    |-content.html
  |
  |–/public_html
      |-password-protect.PHP

    password-protect.PHP is the login page to access the content

    /public_html is the web root directory viewable by the Internet

    content.html is the protected web page

    localstorage is a server directory not accessible by the Internet

password-protect.PHP

<?PHP
     # Check for POST login data, else set initial values
    if (isset($_POST["user"])) {
   $user=$_POST['user'];
     $pass=hash('sha256',$_POST['pass']);
      }
      else {
   $user="";
    $pass="";
     }
     # Check Login Data
     # Password is hashed (SHA256). In this case it is 'admin'.
     if($user == "admin"
    && $pass == "8c6976e5b5410415bde908bd4dee15dfb167a9c873fc4bb8a81f6f2ab448a918")
            {
       # Load content from local storage
     include("../localstorage/content.html");
}
else
{
    # Show login form. Request for username and password
    {?>
<html>
<form method="POST" action="">
Username: <input type="text" name="user"><br/>
Password: <input type="password" name="pass"><br/>
<input type="submit" name="submit" value="Login">
</form>
</body>
<?}
}
?>

Session Timeout

The following is a basic session timeout set for 10 minutes.

<?PHP
session_start();
# Check for session timeout, else initiliaze time
if (isset($_SESSION['timeout'])) {

       # Check Session Time for expiry
       # Time is in seconds. 10 * 60 = 600s = 10 minutes
       if ($_SESSION['timeout'] + 10 * 60 < time()){
  session_destroy();
      }
            }
            else {
       # Initialize time
       $_SESSION['timeout']=time();
       }
?>

Password Protection & Session Timeout

The following adds a session timeout to the password protect script. POST data is stored in SESSION variables until a timeout occurs.

<?PHP
            session_start();
            # Check for session timeout, else initiliaze time
            if (isset($_SESSION['timeout'])) {      
       # Check Session Time for expiry
       # Time is in seconds. 10 * 60 = 600s = 10 minutes
       if ($_SESSION['timeout'] + 30 * 60 < time()){
                &n bsp;  session_destroy();
       }
            }
            else {
       # Initialize variables
       $_SESSION['user']="";
            $_SESSION['pass']="";
       $_SESSION['timeout']=time();
            }

            # Store POST data in session variables
            if (isset($_POST["user"])) {    
       $_SESSION['user']=$_POST['user'];
       $_SESSION['pass']=hash('sha256',$_POST['pass']);
            }

            # Check Login Data             # Password is hashed (SHA256). In this case it is ‘admin’.             if($_SESSION[‘user’] == “admin”             && $_SESSION[‘pass’] == “8c6976e5b5410415bde908bd4dee15dfb167a9c873fc4bb8a81f6f2ab448a918”)             {        # Load content from local storage        include(“../protected/password_protected_content.html”);             }             else             {        # Show login form. Request for username and password        {?>   <html> <body> <form method=”POST” action=””> Username: <input type=”text” name=”user”><br/> Password: <input type=”password” name=”pass”><br/> <input type=”submit” name=”submit” value=”Login”> </form> </body> </html>            <?} } ?>

Store the Password in a File

For increased security, the password can be stored in a local file not accessible by the Internet.
WEBSERVER
  |
  |–/localstorage
  |    |-content.html
  |    |-password.sha
  |
  |–/public_html
      |-password-protect.PHP
where password.sha content is 8c6976e5b5410415bde908bd4dee15dfb167a9c873fc4bb8a81f6f2ab448a918

Retrieving the Password
The stored value can be retrieved by the file_get_contents() command. For example,
# Fetch password
$retrievedpassword = trim(file_get_contents(“../localstorage/password.sha”));
# Check Login Data
if($_SESSION[‘user’] == “admin” && $_SESSION[‘pass’] == $retrievedpassword){
    # Load content from local storage
    include(“../protected/password_protected_content.html”);
}

Simple Login Logout System Using PHP Session

Login and logout system is the most important thing for the user management, session management is one important thing for manage the user for the whole time of login time. for that we have to use session for this. it should have 5 files for this. we have to fetch the same value for the user and check the session and register the session value. and make destroy for logout. let see it detail,

simple login system using php session example

It should need 5 files for this login-logout system, they are

  • login/index page
  • datafetch/usercheck page
  • session/check page
  • welcome/profile page
  • logout page

The above files must me needed for this. we can named it as our wish. let see what i done here. and the database file is needed, if you have any doubt about insert coding check here for insert code
database name –> 2mylogin
table name –> login

DB.PHP

<?PHP
$conn=mysql_connect('localhost','root','');
$db=mysql_select_db('2my4edge',$conn);
?>

INDEX.PHP

<?PHP
     session_start();
?>
<form method="post" name="login" action="login.PHP">
<label for="name" class="labelname"> Username </label>
<input type="text" name="username" id="userid" required="required" /><br />
<label for="name" class="labelname"> Password </label>
<input type="password" name="password" id="passid" required="required"  /><br />
<input type="submit" name="submit" id="submit"  value="Login" />
</form>

in the index page we have to start the session, as the above mentioned. action is performed in login.PHP page.

LOGIN.PHP

<?PHP
include('db.PHP');
session_start();
{
    $user=mysql_real_escape_string($_POST['username']);
    $pass=mysql_real_escape_string($_POST['password']);
    $fetch=mysql_query("SELECT id FROM `login` WHERE username='$user' and password='$pass'");
    $count=mysql_num_rows($fetch);
    if($count!="")
    {
    session_register("sessionusername");
    $_SESSION['login_username']=$user;
    header("Location:profile.PHP");
    }
    else
    {
       header('Location:index.PHP');
    }
}
?>

if the session is registered then go to check the profile.PHP page there session.PHP file is included so the session is checked.

SESSION.PHP

<?PHP
include('db.PHP');
session_start();
$check=$_SESSION['login_username'];
$session=mysql_query("SELECT username FROM `login` WHERE username='$check' ");
$row=mysql_fetch_array($session);
$login_session=$row['username'];
if(!isset($login_session))
{
header("Location:index.PHP");
}
?>

check the session value is correct or not. if the session is value is not set, then again redirect to index.PHP page.

PROFILE.PHP

<?PHP
include("session.PHP");
?> <h3 align="center"> Hellow <?PHP echo $login_session; ?></h3>
<h2 align="center" >Welcome to login system</h2>
<h4 align="center">  click here to <a href="logout.PHP">LogOut</a> </h4>

Assign the logout.PHP page in the profile.PHP page.

LOGOUT.PHP

<?PHP
   session_start();
   if(session_destroy())
   {
      header("Location: index.PHP");
   }
?>

in the logout.PHP page, we should unset or destroy the session value as the above you seen. then locate to index.PHP page and we should have to start the session in all the page.

Output

login:

logout:

php logout template design

One Comment:

  1. slot online says:

    I used to be able to find good information from your content.

Leave a Reply

You must be logged in to post a comment.

Copy link