PHP Cookies and Session Outline| Everything You Need to Know
Session and cookies difference in php ACTE

PHP Cookies and Session Outline | Everything You Need to Know

Last updated on 03rd Jan 2022, Blog, General

About author

Kanagavel (PHP Developer )

Kanagavel is a PHP Developer Expert with 7+ years of experience in PHP, JavaScript, CSS-Cascading Style Sheets, MySQL, Core PHP, and Bootstrap. He spends most of his time researching technology and startups.

(5.0) | 19847 Ratings 681

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.

    • Introduction to Cookie
    • Why and when to use Cookies?
    • Creating Cookies
    • Retrieving the Cookie value
    • Delete Cookies
    • What is a Session?
    • Why and when to use Sessions?
    • Creating a Session
    • Destroying Session Variables
    • Conclusion
Subscribe For Free Demo

    Introduction to Cookie:

  • A cookie is a small file with a maximum size of 4KB that the web server stores on the client computer.
  • Once the cookie is set, all page requests that return the name and value of the cookie.
  • A cookie can only be read from the domain from which it is issued. For example, a cookie set using the domain cannot be read from the domain.
  • Most websites on the Internet display elements from other domains such as advertising. Domains serving these elements may also set their own cookies. These are known as third party cookies.
  • The cookie created by the user can only be visible to them. Other users may not see its value.
  • Most web browsers have options to disable cookies, third party cookies, or both.
  • If so PHP responds by passing a cookie token to the URL.

    Why and when to use Cookies?

  • Http is a stateless protocol; Cookies allow us to track the status of applications using small files stored on the user’s computer. The path to which cookies are stored depends on the browser. Internet Explorer usually stores them in the Temporary Internet Files folder.
  • Personalising User Experience – This is achieved by allowing users to select their preferences. The requested page is personalised based on the preferences set in cookies. Tracking pages visited by users.

    Creating Cookies:

    Now let’s look at the basic syntax used to create a cookie.

    • ?php
    • setcookie(cookie_name, cookie_value, [expiry_time], [cookie_path], [domain], [secure], [httponly]);
    • ,
    • Here,
    • PHP “setcookie” is the PHP function used to create the cookie.
    • “cookie_name” is the name of the cookie that the server will use when retrieving its value from the $_COOKIE array variable. It’s mandatory.
    • “cookie_value” is the value of the cookie and is mandatory
    • “[expiry_time]” is optional; This can be used to set an expiration time for a cookie such as 1 hour. Time is set using the PHP time() function plus or minus, which is the number of seconds greater than 0 i.e. time() + 3600 for 1 hour.
    • “[cookie_path]” is optional; This can be used to set the cookie path on the server. The forward slash “/” means that the cookie will be made available across the domain. Sub directories limit cookie access to subdomains.
    • “[domain]” is optional, it can be used to define cookie access hierarchy i.e. means entire domain while refers to cookie access to www.sub.cookiedomain. com and its subs. Domain Note that a subdomain of a subdomain is possible as long as the total number of characters does not exceed 253 characters.
    • “[secure]” is optional, the default is false. It is used to determine whether the cookie is sent via https if it is set to true or http if it is set to false.
    • “[httponly]” is optional. If it is set to true, then only client side scripting languages ​​i.e JavaScript cannot access them.
    • Note: The PHP set cookie function must be executed before the HTML opening tag.
    • Let’s now look at an example that uses cookies.
    • We will create a basic program that allows us to store the username in a cookie that expires after ten seconds.
    • The code below shows the implementation of the above example “cookies.php”.
    • setCookie(“user_name”, “master 99”, time() + 60, ‘/’); // expires after 60 seconds
    • echo ‘The cookie has been set for 60 seconds’;
    • ,
    • Output:
    • Cookie has been set for 60 seconds

      Retrieving the Cookie value:

      • Create another file named “cookies_read.php” with the following code.
      • php
      • print_r($_cookie); //output the contents of the cookie array variable
      • ,
      • Output:
      • Array ( [PHPSESSID] => h5onbf7pctbr0t68adugdp2611 [user_name] => master99)
      • Note: $_COOKIE is a PHP built in super global variable.
      • It contains the names and values ​​of all set cookies.
      • the number of values ​​that
      • Might depend on the memory size set in php.ini in the $_COOKIE array.
      • The default value is 1GB.
      • Testing our application.
      • Let’s say you have saved your php files in the photos folder.
      • Step 1 – Open your web browser and enter the URL http://localhost/phptuts/cookies_read.php
      • PHP Cookies and PHP Sessions
      • Note: Only an empty array is displayed
      • Step 2 – Browser to URL http://localhost/phptuts/cookies.php
      • PHP Cookies and PHP Sessions
      • Step 3 – Go back to the first tab and then click on the Refresh button
      • PHP Cookies and PHP Sessions
      • Wait a minute and click on the refresh button again. what results did you get

      Delete Cookies:

      If you want to destroy a cookie before its expiration time, you set the expiration time to a time that has already passed. Create a new file named cookie_destroy.php with the following code:

      • setcookie(“user_name”, “master 99”, time() – 360, ‘/’);
      • ,
      • Repeat steps 1 to 3 from the above section to get the cookie value.
      • Open the url http://localhost/phptuts/cookie_destroy.php
      • Switch to URL http://localhost/phptuts/cookies_read.php What result does it display?

      What is a Session?

    • A session is a global variable stored on the server.
    • Each session is assigned a unique ID which is used to retrieve the stored values.
    • Whenever a session is created, a cookie containing the unique session ID is stored on the user’s computer and returned with each request to the server. If the client browser does not support cookies, the unique php session id is displayed in the URL
    • Sessions have the ability to store a relatively large amount of data as compared to cookies.
    • Session values ​​are automatically deleted when the browser is closed. If you want to store the values permanently, you should store them in the database.
    • Like the $_COOKIE array variable, session variables are stored in the $_SESSION array variable. Like cookies, the session must begin before any HTML tag.

      Why and when to use Sessions?

    • You want to store important information like user IDs more securely on a server where malicious users can’t mess with them.
    • You want to pass values ​​from one page to another.
    • You may want the cookies option on browsers that do not support cookies.
    • You want to store global variables in an efficient and more secure way than passing them in the URL
    • You are developing a shopping cart-like application with a capacity larger than 4KB to temporarily store information.

    Course Curriculum

    Develop Your Skills with Advanced PHP Certification Training

    Weekday / Weekend BatchesSee Batch Details

      Creating a Session:

      To create a session, you must first call the PHP session_start function and then store its values ​​in the $_SESSION array variable.

      Let’s say we want to know how many times a page has been loaded, we can use a session to do that.

      The code below shows how to create and retrieve values ​​from sessions

      • session_start(); // start php_session function
      • if (isset($_SESSION[‘page_count’]))
      • ,
      • $_SESSION[‘page_count’] += 1;
      • ,
      • Otherwise
      • ,
      • $_SESSION[‘page_count’] = 1;
      • ,
      • echo ‘You are visitor number’. $_session[‘page_count’];
      • ,
      • Output:
      • You are visitor number 1. Huh

      Destroying Session Variables:

      The session_destroy() function is used to destroy the entire Php session variable. If you only want to destroy a single session item, you use the unset() function. The code below shows how to use both methods.

      • ?php
      • session_destroy(); // destroy the entire session
      • ,
      • unset($_SESSION[‘product’]); // Destroy the product session item
      • ,
      • session_destroy deletes all session data, including cookies associated with the session.
      • Unset only frees individual session variables.
      • Other data remains intact.

    Lean PHP Developer Sample Resumes! Download & Edit, Get Noticed by Top Employers! Download


    • Cookies are small files saved on the user’s computer
    • Cookies can be read only from the issuer domain
    • Cookies may have an expiry time, if this is not set, the cookie expires when the browser is closed
    • Sessions are like global variables stored on the server
    • Each session is assigned a unique ID which is used to track the user’s variables.
    • Both the cookies and the session must be initiated before any HTML tags can be sent to the browser.
    • Cookies are often used to identify the user. A cookie is a small file that a server embeds on the user’s computer. Every time the same computer requests a page with a browser, it will also send a cookie. With PHP, you can create and retrieve cookie values.
    • When you’re done with an application, you open it, make some changes, and then you close it. It’s more like a session. The computer knows who you are. It knows when you start the application and when it ends. But there’s a problem on the Internet: the web server doesn’t know who you are or what you do, because HTTP doesn’t maintain address state.
    • Session variables solve this problem by storing user information used across multiple pages (such as username, favourite colour, etc.). By default, session variables last until the user closes the browser.
    • Therefore; Session variables hold information about a single user, and are available to all pages in an application.

Are you looking training with Right Jobs?

Contact Us
Get Training Quote for Free