Quick Contact

    Session, Cookie, Query String

    State management is used to help web applications to maintain their state in several HTTP requests when needed. PHP provide two different techniques to manage the state of your web application.

    Server-Side State Management: It is state management at server side. It is done using:

    • Session

    Client-Side State Management: It is state management at server side. It is done using:

    • Query String
    • Cookies

    Let’s discuss management strategic in brief:

    Session

    A normal HTML website will not pass data from one page to another. In other words, all information is forgotten when a new page is loaded. This makes it quite a problem for tasks like a shopping cart, which requires data(the user’s selected product) to be remembered from one page to the next.

    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.).

    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.

    Cookies

    A cookie is a small bit of information stored on a viewer’s computer by his or her web browser by request from a web page.

    The information is constantly passed in HTTP headers between the browser and web server. The browser sends the current cookie as part of its request to the server and the server sends updates to the data back to the user as part of its response. The size of a cookie depends on the browser but in general should not exceed 1K (1,024 bytes).

    The information can really be anything. It can be a name, the number of visits to the site, web-based shopping cart information, personal viewing preferences or anything else that can be used to help provide customized content to the user.

    Query string

    The information can be sent across the web pages. This information is called query string. This query string can be passed from one page to another by appending it to the address of the page. You can pass more than one query string by inserting the & sign between the query strings. A query string can contain two things: the query string ID and its value. The query string passed across the web pages is stored in $_REQUEST, $_GET, or $_POST variable. Whether you passed the query string by using GET or POST method, it is stored in $_REQUEST variable.

    If you want to access the query string you can use these variables. You should note that whether the query string is passed by the GET or POST method it can be accessed by using the $_REQUEST variable. If you want to use $_GET variable to access the query string, the form method need to be GET. Also, you can use $_POST variable to get the query string if the form method is POST.

    What Session Control is?

    Sessions are a simple way to store data for individual users against a unique session ID. This can be used to persist state information between page requests. Session IDs are normally sent to the browser via session cookies and the ID is used to retrieve existing session data. The absence of an ID or session cookie lets PHP know to create a new session, and generate a new session ID.

    By default, PHP uses the internal files save handler which is set by session.save_handler. This saves session data on the server at the location specified by the session.save_path configuration directive.

    Sessions can be started manually using the session_start() function. If the session.auto_start directive is set to 1, a session will automatically start on request startup.

    Sessions normally shutdown automatically when PHP is finished executing a script but can be manually shutdown using the session_write_close() function.

    Understanding Basic Session Functionality

    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.

    The location of the temporary file is determined by a setting in the php.ini file called session.save_path. Before using any session, variable make sure you have setup this path.

    When a session is started following things happen −

    PHP first creates a unique identifier for that particular session which is a random string of 32 hexadecimal numbers such as 3c7foj34c3jj973hjkop2fc937e3443.

    A cookie called PHPSESSID is automatically sent to the user’s computer to store unique session identification string.

    A file is automatically created on the server in the designated temporary directory and bears the name of the unique identifier prefixed by sess_ iesess_3c7foj34c3jj973hjkop2fc937e3443.

    When a PHP script wants to retrieve the value from a session variable, PHP automatically gets the unique session identifier string from the PHPSESSID cookie and then looks in its temporary directory for the file bearing that name and a validation can be done by comparing both values.

    A session ends when the user loses the browser or after leaving the site, the server will terminate the session after a predetermined period of time, commonly 30 minutes duration.

    Starting a PHP 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.

    Below is the PHP code to start a new session:

    <?php
    session_start();
    ?>
    
    Registering Session variables

    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:

    <?php
       session_start();
       if( isset( $_SESSION['counter'] ) ) {
          $_SESSION['counter'] += 1;
       }else {
          $_SESSION['counter'] = 1;
       }
       $msg = "You have visited this page ".  $_SESSION['counter'];
       $msg .= "in this session.";
    ?>
    <html>
    <head>
    <title>Setting up a PHP session</title>
    </head>
    <body>
    <?php  echo ( $msg ); ?>
    </body>
    </html>
    

    It will produce the following result:

    You have visited this page 1in this session.
    Using Session Variables

    We will use the session information we set on any php file

    Notice that session variables are not passed individually to each new page, instead they are retrieved from the session we open at the beginning of each page (session_start()).

    Also notice that all session variable values are stored in the global $_SESSION variable: An example of the code is:

    <?php
    session_start();
    ?>
    <!DOCTYPE html>
    <html>
    <body>
    <?php
    // Echo session variables that were set on previous page
    echo "Favorite color is " . $_SESSION["favcolor"] . ".<br>";
    echo "Favorite animal is " . $_SESSION["favanimal"] . ".";
    ?>
    </body>
    </html>
    

    Another way to show all the session variable values for a user session is to run the following code:

    <?php
    session_start();
    ?>
    <!DOCTYPE html>
    <html>
    <body>
    <?php
    print_r($_SESSION);
    ?>
    </body>
    </html>
    
    Modify a PHP Session Variable

    To change a session variable, we can overwrite it as given in the below program:

    <?php
    session_start();
    ?>
    <!DOCTYPE html>
    <html>
    <body>
    <?php
    // to change a session variable, just overwrite it 
    $_SESSION["favcolor"] = "yellow";
    print_r($_SESSION);
    ?>
    </body>
    </html>
    

    The output will be:

    Array ( [favcolor] => yellow )
    Destroying the variables and Session

    To delete only a certain session data, the unset feature can be used with the corresponding session variable in the $_SESSION associative array.

    The PHP code to unset only the Rollnumber session variable from the associative session array:

    <?php
    session_start();
    if(isset($_SESSION["Name"])){
        unset($_SESSION["Rollnumber"]);
    }
    ?>
    
    Destroying Complete Session:

    The session_destroy() function is used to completely destroy a session. The session_destroy() function does not require any argument.

    <?php
    session_start();
    session_destroy();
    ?>
    
    What is a Cookie?

    PHP cookie is a small piece of information which is stored at client browser. It is used to recognize the user.

    Cookie is created at server side and saved to client browser. Each time when client sends request to the server, cookie is embedded with request. Such way, cookie can be received at the server side. Cookies are text files stored on the client computer and they are kept of use tracking purpose. PHP transparently supports HTTP cookies.

    There are three steps involved in identifying returning users:

    • Server script sends a set of cookies to the browser. For example, name, age, or identification number etc.
    • Browser stores this information on local machine for future use.
    • When next time browser sends any request to web server then it sends those cookies information to the server and server uses that information to identify the user.
    The Anatomy of a Cookie

    Cookies are usually set in an HTTP header (although JavaScript can also set a cookie directly on a browser). A PHP script that sets a cookie might send headers that look something like this:

    HTTP/1.1 200 OK
    Date: Fri, 04 Feb 2000 21:03:38 GMT
    Server: Apache/1.3.9 (UNIX) PHP/4.0b3
    Set-Cookie: name=xyz; expires=Friday, 04-Feb-07 22:03:38 GMT; 
    path=/; domain=tutorialspoint.com
    Connection: close
    Content-Type: text/html
    

    As you can see, the Set-Cookie header contains a name value pair, a GMT date, a path and a domain. The name and value will be URL encoded. The expires field is an instruction to the browser to forget the cookie after the given time and date.

    If the browser is configured to store cookies, it will then keep this information until the expiry date. If the user points the browser at any page that matches the path and domain of the cookie, it will resend the cookie to the server. The browser’s headers might look something like this:

    GET / HTTP/1.0
    Connection: Keep-Alive
    User-Agent: Mozilla/4.6 (X11; I; Linux 2.2.6-15apmac ppc)
    Host: zink.demon.co.uk:1126
    Accept: image/gif, */*
    Accept-Encoding: gzip
    Accept-Language: en
    Accept-Charset: iso-8859-1,*,utf-8
    Cookie: name=xyz
    

    A PHP script will then have access to the cookie in the environmental variables $_COOKIE or $HTTP_COOKIE_VARS[] which holds all cookie names and values. Above cookie can be accessed using $HTTP_COOKIE_VARS[“name”].

    Setting Cookies with PHP

    PHP provided setcookie() function to set a cookie. This function requires up to six arguments and should be called before <html> tag. For each cookie this function has to be called separately.

    setcookie(name, value, expire, path, domain, security);

    Here is the detail of all the arguments:

    • Name: This sets the name of the cookie and is stored in an environment variable called HTTP_COOKIE_VARS. This variable is used while accessing cookies.
    • Value: This sets the value of the named variable and is the content that you want to store.
    • Expiry: This specify a future time in seconds since 00:00:00 GMT on 1st Jan 1970. After this time cookie will become inaccessible. If this parameter is not set, then cookie will automatically expire when the Web Browser is closed.
    • Path: This specifies the directories for which the cookie is valid. A single forward slash character permits the cookie to be valid for all directories.
    • Domain: This can be used to specify the domain name in very large domains and must contain at least two periods to be valid. All cookies are only valid for the host and domain which created them.
    • Security: This can be set to 1 to specify that the cookie should only be sent by secure transmission using HTTPS otherwise set to 0 which mean cookie can be sent by regular HTTP.

    Following example will create two cookies name and age these cookies will be expired after one hour.

    <?php
       setcookie("name", "John Watkin", time()+3600, "/","", 0);
       setcookie("age", "36", time()+3600, "/", "",  0);
    ?>
    <html>
    <head>
    <title>Setting Cookies with PHP</title>
    </head>
    <body>
    <?php echo "Set Cookies"?>
    </body>
    </html>
    
    Using Cookies with Sessions

    PHP provides many ways to use cookies. Simplest way is to use either $_COOKIE or $HTTP_COOKIE_VARS variables. Following example will access all the cookies set in above example.

    <html>
    <head>
    <title>Accessing Cookies with PHP</title>
    </head>
    <body>
    <?php
             echo $_COOKIE["name"]. "<br />
             /* is equivalent to */
             echo $HTTP_COOKIE_VARS["name"]. "<br />";
             echo $_COOKIE["age"] . "<br />";
             /* is equivalent to */
             echo $HTTP_COOKIE_VARS["age"] . "<br />";
          ?>
    </body>
    </html>
    

    You can use isset() function to check if a cookie is set or not.

    <html>
    <head>
    <title>Accessing Cookies with PHP</title>
    </head>
    <body>
    <?php
             if( isset($_COOKIE["name"]))
                echo "Welcome " . $_COOKIE["name"] . "<br />";
             else
                echo "Sorry... Not recognized" . "<br />";
          ?>
    </body>
    </html>
    
    Cookie-based sessions

    PHP provides a cookie-based implementation for session management. The $_SESSION array is used for storing session data. PHP automatically generates a session ID and sends a session cookie containing this session ID to the client machine. The PHP functions for session management are listed in the following table.

    The basic login process begins with the display of two fields for the user name and password. The following code shows the HTML file used for the display of the login prompt.

    <html><head><title>Login</title></head>
    <body>
    <form method="post" action="login.php">
    <center>
    <table border=0>
    <tr>
    <td><label for="username">Username:</label></td>
    <td><input type="text" id="username" name="username" maxlength="50" /></td>
    </tr><tr>
    <td><label for="passwd">Password:</label></td>
    <td><input type="password" id="passwd" name="passwd" /></td>
    </tr>
    </table><br />
    <input type="submit" value="Log in" />
    </form>
    </body></html>
    
    Session status

    Since the session has been established, you can test the availability of persistence for the user name and user ID. For this, let’s create a small script called status.php. This script calls the session_start() function. Since the session cookie is already available in the client machine, calling the session_start() function looks at the session ID and loads the appropriate session variables with previous values on the server machine. Hence, calling $_SESSION[‘username’] or $_SESSION[‘id’] will retrieve the data stored through the login.php script file. The following is what the status.php script looks like:

    <?php
    /*status.php*/
    session_start();
    //Check for valid session. Exit from page if not valid.
    if(!isset($_SESSION['username']) && !isset($_SESSION['id'])) {
    print("<center><h1>invalid session!</h1><br />n<a href="loginform.html">Login</a>");
    exit();
    }
    printf("<center><b>Welcome %s! Your id is: %d</b>",$_SESSION['username'],$_SESSION['id']);
    printf("<br /><a href="logout.php">Logout %s</a></center>",$_SESSION['username']);
    ?>
    
    Log out

    The logout operation is contained in the script called logout.php. The script calls the session_destroy() function, which kills the session cookie and clears the session variables. The following is what the logout script looks like:

    <?php
    session_start();
    printf("<center><h1>Good Bye %s!</h1><br /><a href="loginform.html">Go to login page!</a><br /><a href="status.php">Get Status</a></center>n",$_SESSION['username']);
    session_destroy();
    ?
    
    PHP Create/Retrieve a Cookie

    The following example creates a cookie named user with the value “John Doe”. The cookie will expire after 30 days (86400 * 30). The / means that the cookie is available in entire website (otherwise, select the directory you prefer).

    We then retrieve the value of the cookie user (using the global variable $_COOKIE). We also use the isset() function to find out if the cookie is set:

    An example is given as:

    <?php
    $cookie_name = "user";
    $cookie_value = "John Doe";
    setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
    ?>
    <html>
    <body>
    <?php
    if(!isset($_COOKIE[$cookie_name])) {
        echo "Cookie named '" . $cookie_name . "' is not set!";
    } else {
        echo "Cookie '" . $cookie_name . "' is set!<br>";
        echo "Value is: " . $_COOKIE[$cookie_name];
    }
    ?>
    
    </body>
    </html>
    

    Note: The setcookie() function must appear BEFORE the <html> tag.

    Note: The value of the cookie is automatically URLencoded when sending the cookie, and automatically decoded when received (to prevent URLencoding, use setrawcookie() instead).

    Modify a Cookie Value

    To modify a cookie, just set (again) the cookie using the setcookie() function:

    An example is given as:

    <?php
    $cookie_name = "user";
    $cookie_value = "Alex Porter";
    setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
    ?>
    <html>
    <body>
    <?php
    if(!isset($_COOKIE[$cookie_name])) {
        echo "Cookie named '" . $cookie_name . "' is not set!";
    } else {
        echo "Cookie '" . $cookie_name . "' is set!<br>";
        echo "Value is: " . $_COOKIE[$cookie_name];
    }
    ?>
    </body>
    </html>>
    
    Deleting Cookies

    To delete a cookie, use the setcookie() function with an expiration date in the past:

    An example is given below:

    <?php
    // set the expiration date to one hour ago
    setcookie("user", "", time() - 3600);
    ?>
    <html>
    <body>
    <?php
    echo "Cookie 'user' is deleted.";
    ?>
    </body>
    </html>
    
    Implementing Query String

    The information can be sent across the web pages is called query string.A QueryString is a collection of characters input to a computer or web browser. A Query String is helpful when we want to transfer a value from one page to another. When we need to pass content between the HTML pages or php Web Forms . It is basically used for identifying data appearing after this separating symbol.

    A query string can contain two things: the query string ID and its value. The query string passed across the web pages is stored in $_REQUEST, $_GET, or $_POST variable. Whether you passed the query string by using GET or POST method, it is stored in $_REQUEST variable. If you want to access the query string you can use these variables. You should note that whether the query string is passed by the GET or POST method it can be accessed by using the $_REQUEST variable. If you want to use $_GET variable to access the query string, the form method need to be GET. Also, you can use $_POST variable to get the query string if the form method is POST.

    In the following example, the query strings username and email(the names of textboxes) are passed from a page called login.php to another page called welcome.php when you click the submit button.

    Login.php:
    <html>
    <head>
    <title>Login form</title>
    </head>
    <body>
    <form action="welcome.php" method=”get”>
    <table>
    <tr>
    <td>User name:</td><td><input type="text" name="username" ></td>
    </tr>
    <tr>
    <td>E-mail: </td><td><input type="text" name="email" ></td>
    </tr>
    <tr>
    <td><input type="submit" name="sub" value="submit"></td>
    </tr>
    </table>
    </form>
    </body>
    </html>
    
    welcome.php:
    <?php
    echo "<strong>Welcome ".$_GET['username']. "!</strong><br/>";
    echo "Please remember this e-mail: ".$_GET['email']. " for later use.";
    ?>
    
    Summary

    The following below points summarize the topics discussed above:

    • State management is used to help web applications to maintain their state in several HTTP requests when needed.
    • Server-Side State Management and Client-Side State Management are two different techniques used by PHP to manage the state of your web application.
    • PHP sessions are used as alternative way to make data accessible across the various pages of an entire website.
    • 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.
    • A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user’s computer.
    • Cookies are sent to server each time the request is sent. With PHP, you can both create and retrieve cookie values.
    • Query String are the information can be sent across the web pages. Query string follows proper syntax for different function.

    Copyright 1999- Ducat Creative, All rights reserved.