PHP Cookies and Session Outline | Everything You Need to Know
Last updated on 03rd Jan 2022, Blog, General
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
- Creating Cookies
- Retrieving the Cookie value
- Delete Cookies
- What is a Session?
- Why and when to use Sessions?
- Creating a Session
- Destroying Session Variables
- 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 www.acte.com domain cannot be read from the career.acte.com 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.
Introduction to Cookie:
- 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.
- setcookie(cookie_name, cookie_value, [expiry_time], [cookie_path], [domain], [secure], [httponly]);
- 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. www.cookiedomain.com means entire domain while www.sub.cookiedomain.com 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.
- Note: The PHP set cookie function must be executed before the HTML opening tag.
- 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’;
- Cookie has been set for 60 seconds
- Create another file named “cookies_read.php” with the following code.
- print_r($_cookie); //output the contents of the cookie array variable
- 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
- 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?
- 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.
- 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.
- session_start(); // start php_session function
- if (isset($_SESSION[‘page_count’]))
- $_SESSION[‘page_count’] += 1;
- $_SESSION[‘page_count’] = 1;
- echo ‘You are visitor number’. $_session[‘page_count’];
- You are visitor number 1. Huh
- 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.
- 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.
Now let’s look at the basic syntax used to create a cookie.
Retrieving the Cookie value:
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:
What is a Session?
Why and when to use Sessions?
Develop Your Skills with Advanced PHP Certification TrainingWeekday / 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
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.