Php user session cookie

PHP Session & PHP Cookies with Example

A cookie is a small file with the maximum size of 4KB that the web server stores on the client computer.

Once a cookie has been set, all page requests that follow return the cookie name and value.

A cookie can only be read from the domain that it has been issued from. For example, a cookie set using the domain www.guru99.com can not be read from the domain career.guru99.com.

Most of the websites on the internet display elements from other domains such as advertising. The domains serving these elements can also set their own cookies. These are known as third party cookies.

A cookie created by a user can only be visible to them. Other users cannot see its value.

Most web browsers have options for disabling cookies, third party cookies or both.

If this is the case then PHP responds by passing the cookie token in the URL.

The diagram shown below illustrates how cookies work.

What is Cookie

1) A user requests for a page that stores cookies

2) The server sets the cookie on the user’s computer

3) Other page requests from the user will return the cookie name and value

Why and when to use Cookies?

  • Http is a stateless protocol; cookies allow us to track the state of the application using small files stored on the user’s computer.The path were the cookies are stored depends on the browser.Internet Explorer usually stores them in Temporal Internet Files folder.
  • Personalizing the user experience – this is achieved by allowing users to select their preferences.The page requested that follow are personalized based on the set preferences in the cookies.
  • Tracking the pages visited by a user

Creating Cookies

Let’s now look at the basic syntax used to create a cookie.

  • 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 its mandatory
  • “[expiry_time]” is optional; it can be used to set the expiry time for the cookie such as 1 hour. The time is set using the PHP time() functions plus or minus a number of seconds greater than 0 i.e. time() + 3600 for 1 hour.
  • “[cookie_path]” is optional; it can be used to set the cookie path on the server. The forward slash “/” means that the cookie will be made available on the entire domain. Sub directories limit the cookie access to the subdomain.
  • “[domain]” is optional, it can be used to define the cookie access hierarchy i.e. www.cookiedomain.com means entire domain while www.sub.cookiedomain.com limits the cookie access to www.sub.cookiedomain.com and its sub domains. Note it’s possible to have a subdomain of a subdomain as long as the total characters do 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.
Читайте также:  List style position inside css

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 user name in a cookie that expires after ten seconds.

The code below shows the implementation of the above example “cookies.php”.

the cookie has been set for 60 seconds

Create another file named “cookies_read.php” with the following code.

Array ( [PHPSESSID] => h5onbf7pctbr0t68adugdp2611 [user_name] => Guru99 )

Note: $_COOKIE is a PHP built in super global variable.

It contains the names and values of all the set cookies.

The number of values that the

$_COOKIE array can contain depends on the memory size set in php.ini.

Let’s assume you have saved your PHP files in phptus folder.

  • Step 1 – open your web browser and enter the URL http://localhost/phptuts/cookies_read.php

Retrieving the Cookie value

Note: Only an empty array has been displayed

Retrieving the Cookie value

Retrieving the Cookie value

Wait for a minute then click on refresh button again. What results did you get?

Delete Cookies

  • If you want to destroy a cookie before its expiry time, then you set the expiry time to a time that has already passed.
  • Create a new filed named cookie_destroy.php with the following code
  • Repeat steps 1 through to 3 from the above section on retrieving cookie values.
  • Open the URL http://localhost/phptuts/cookie_destroy.php
  • Switch to the URL http://localhost/phptuts/cookies_read.php what results 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 stored values.
  • Whenever a session is created, a cookie containing the unique session id is stored on the user’s computer and returned with every 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 capacity to store relatively large data compared to cookies.
  • The session values are automatically deleted when the browser is closed. If you want to store the values permanently, then you should store them in the database.
  • Just like the $_COOKIE array variable, session variables are stored in the $_SESSION array variable. Just like cookies, the session must be started before any HTML tags.

Why and when to use Sessions?

  • You want to store important information such as the user id more securely on the server where malicious users cannot temper with them.
  • You want to pass values from one page to another.
  • You want the alternative to cookies on browsers that do not support cookies.
  • You want to store global variables in an efficient and more secure way compared to passing them in the URL
  • You are developing an application such as a shopping cart that has to temporary store information with a capacity larger than 4KB.
Читайте также:  Javascript array merge all

Creating a Session

In order to create a session, you must first call the PHP session_start function and then store your values in the $_SESSION array variable.

Let’s suppose we want to know the number of times that 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

 else < $_SESSION['page_count'] = 1; >echo 'You are visitor number ' . $_SESSION['page_count']; ?>

Destroying Session Variables

The session_destroy() function is used to destroy the whole Php session variables.

If you want to destroy only a session single item, you use the unset() function.

The code below illustrates how to use both methods.

Session_destroy removes all the session data including cookies associated with the session.

Unset only frees the individual session variables.

Other data remains intact.

Summary

  • Cookies are small files saved on the user’s computer
  • Cookies can only be read from the issuing domain
  • Cookies can have an expiry time, if it is not set, then the cookie expires when the browser is closed
  • Sessions are like global variables stored on the server
  • Each session is given a unique identification id that is used to track the variables for a user.
  • Both cookies and sessions must be started before any HTML tags have been sent to the browser.

Источник

Understanding Cookies and Sessions in PHP

Have you ever wondered how your details and recent activities on a website are being saved and remembered by your system? This happens with the help of cookies and sessions. In this article, we will discuss what cookies and sessions are, how cookies and sessions work in PHP, How cookies and sessions are created, accessed, modified, and deleted, and the difference between cookies and sessions in PHP.

The Idea Behind Cookies and Sessions in PHP.

Image description

If you want to know more about the internet, Cookies and Sessions are two essential things you need to know. The idea behind them is that they both save the information of the user, such as login details, recent products checked, etc. Cookies are automatically saved whenever a new web page is opened or reloaded. Whenever cookies request user information from the server. The server sets a Session ID in the cookies. The server uses that session ID to identify the cookies where the request is coming from.

What Are Cookies in PHP?

Cookies are small files of information that are sent to a browser to store a user’s information from a particular visited website. Cookies stores user information from a website in the browser only and use that information to identify the user when next the user tries to use visit the same website in the browser

Setting Cookies in PHP

The setcookie() function is used to set a cookie in PHP, it accepts up to six arguments in general, which are all in strings.

Syntax:

---Php setcookie(name, value, expire, path, domain, secure) 

The setcookie() function should be called first before any other code is called or executed, just like the code below:

Parameter Description
Name This contains the name of the cookie.
Value This contains the value of the cookie. This could be in a string or integer form
Expire This will contain the expiration date, of the cookie. If omitted, it will take the default value(0s), and immediately after the user reloads or closes the web page the data in the cookies will be lost. Optional
Path This will contain the path of the cookie in the webserver. Optional.
Domain This will contain the domain works. For example, www.example.com. Optional
Secure Optional.
Читайте также:  Range что означает python

The name: ‘Username’, value: ‘Dennis’, expire: time() + 86400, path: ‘/’. we will leave the remaining parameters since they are optional time() is a function that returns the current time.

There are different methods you can access a cookie in PHP, but we take the easy method to achieve this by using either $_COOKIE or $HTTP_COOKIE_VARS .

---Php   "; //Accessing a cookie with $HTTP_COOKIE_VARS echo $HTTP_COOKIE_VARS["Username"] . "
"; ?>

The setcookie() function can be used to delete cookies in PHP just the same as creating a cookie. The only difference is to reverse the expiry time to a past time.
The example below illustrates how we can achieve that.

What Are Sessions in PHP?

Sessions save the user information and activity on a website to a file in a temporary directory on the server. They make user-stored information available across all other websites the browser This user data are stored temporarily on the server. By default, when a user refreshes or closes the browser the user data vanishes from the server.

How to Start a Session in PHP.

session_start() is a function that is used to start a session in PHP.
PHP $_SESSION is a PHP global variable. It is also an array that stores a session variable whenever a session creates a temporary file in the server. Let’s start a new PHP session and set a few session variables to the $_SESSION :

How to Get a Session Variable Values and display it

Here, we will get the Session variable from the previous code.
View this example to get a better understanding:

How to Modify a Session Variable

How to destroy a session in PHP.

To remove all variable values from a session, you have to make use of two functions, session_unset() and session_destroy() . These functions have different purposes.
Follow this example below:

Differences Between Cookies and Sessions in PHP.

Cookies Sessions
Cookies stores user data in the browser Sessions stores user data in the server
Cookies store user data permanently till the user decides to discard it Sessions stores user data temporarily and dispose of it when the user refreshes or closes the browser.
Cookies can easily be accessed by hackers since it stores user data in the browser Sessions cannot be accessed by hackers since it stores a user data on the server
Cookies contain a minimal amount of storage space(4kb) to store user data Sessions contain a large amount of storage space(128MB) to store user data

Conclusion

We learned what Cookies and Sessions are in PHP, their purpose, How they work, and the difference between them. I hope this was helpful. Thank you for taking the time to read this.

Источник

Оцените статью