PHP State Management – Cookies & Sessions

PHP Cookie

PHP cookie is a small piece of information or file that is storedPHP cookies Diagram in user’s browser. It is often used to identify the user. The cookie is created at server side and saved to user’s browser. Each time when the user sends the request to the server then the cookie is embedded with a request. The cookie can be received at the server side. With the help of  PHP, you can both create, sent and retrieve the cookie values.

PHP setcookie() function

In PHP, you can set cookies by using the setcookie() function or setrawcookie() function. PHP setcookie() function defines to set a cookie and cookies are part of the with HTTP headers, so setcookie() function must be called before any output is sent to the browser. Once the cookie is set, then you can access it by $_COOKIE superglobal variable. And the Cookie values can also exist in $_REQUEST. The setcookie() function requires up to six arguments and should be appear before the <html> tag. For each cookie, setcookie() function has to be called separately.

And it’s a setcookie (name, value, expire, path, domain, security);

Syntax:-

bool setcookie ( string $name [, string $value [, int $expire = 0 [, string $path [, string $domain [, bool $secure = false [, bool $httponly = false ]]]]]] )  

Example:-

  1. setcookie(“CookieName”, “CookieValue”, time()+1*60*60, “/mypath/”, “mydomain.com”, 1);  
  2. setcookie(“CookieName”, “CookieValue”, time()+1*60*60);   //using expiry in 1 hour(1*60*60 seconds or 3600 seconds)  
  3. setcookie(“CookieName”, “CookieValue”);    /* defining name and value of cookie only*/  

PHP $_COOKIE

The PHP $_COOKIE superglobal variable is used to get cookie.

Example:-

  1. $value = $_COOKIE[“CookieName”];   //returns the cookie value  

PHP Cookie Example

File: cookie.phpCreate PHP cookie

First Output:-

Sorry, cookie is not found!

Firstly, the cookie is not set. But, when if you refresh the page,then you will see cookie is set now.

Second Output after refresh browser:-create cookies in PHP output

PHP Delete Cookie

If you want to set the expiration date in past, then the cookie will be deleted.

The following way you can follow for delete a cookie:-Delete a cookie

Output:-Cookie Delete

PHP Session

For storing and passing the temporary information from PHP state management one page to an another PHP Session is used. For example shopping websites where we want to store and pass the cart information from one page to another like username, product name, product price, product code. PHP session creates a file in the temporary directory on a server where it is registered session variables and stores their values. And the data will be available on all the pages during the visiting on site. PHP session always creates a unique id for each browser user to recognize the user and avoid conflict between multiple browsers. 

Watch the video wherein the concept is explained briefly with examples –

PHP SESSION_START() function

Here in PHP, You have a session_start() function for startup the session. This seesion_start() function starts a new session or resumes the existing session. In case, You already created session then it will return the existing session. And, On the other hand, if a session is not already created then firstly it will create a session and return new session.

Syntax:-

bool session_start ( void )

Example:-

session_start();

PHP $_SESSION

PHP $_SESSION is an associative array whose contains all the session variables. $_SESSION is used to set and get the session variable values in PHP. The Session variables are set with the PHP global variable is $_SESSION.

Example: Store information

  1. $_SESSION[“user”] = “Sachin”;  

Example: Get information

  1. echo $_SESSION[“user”];  

PHP Session Example

Let’s create a new page called “session.php”. In this page, you start a new PHP session and set some session variables.

File: session.php create a PHP session1.php

File: session2.php create a PHP session2.php                            

Output:- create a session

                             session created in PHP

PHP Session Counter Example

File: sessioncounter.php   Session Count in PHP state management                    

Output:- Session Count in PHP state management

PHP Destroying Session – session_destroy()

After Creating the session, if you want to delete all the session variables completely, then in case SESSION_DESTROY() function will help you to achieve this goal.Session Destroy in PHP state management

Output:- Session Destroyed in PHP state management


Session Destroyed in PHP state management

Watch this tutorial on YouTube –

Hope this article was helpful. If you have any topic in mind, on which you want us to write blog, feel free to mention that in the comment section below.

Happy programming !

4 thoughts on “PHP State Management – Cookies & Sessions

  1. I must show thanks to this writer for rescuing me from this particular problem. Right after scouting throughout the world wide web and obtaining recommendations that were not beneficial, I figured my life was well over. Living without the approaches to the difficulties you’ve solved as a result of your entire guideline is a serious case, as well as ones which might have in a negative way damaged my career if I hadn’t discovered your blog post. Your actual natural talent and kindness in touching the whole thing was tremendous. I don’t know what I would have done if I hadn’t encountered such a stuff like this. I can also at this time look forward to my future. Thanks for your time very much for your high quality and result oriented guide. I will not think twice to propose the website to anybody who should have support about this subject.

Leave a Reply

Your email address will not be published. Required fields are marked *