Sessions and cookies in PHP

HTTP Request Methods in PHP
File Handling in PHP

To correctly complete request and response activities, web pages must temporarily or permanently store data. Almost every web development language has sessions and cookies to store client and server information, delivering a seamless and secure experience. This article will go over PHP sessions and cookies in detail.

What are Cookies in PHP?

Cookies are little files that are saved on the client’s computer and can include information about the user, the request, the answer, and the server. They are delivered to the server alongside requests, letting the server to identify the user. A user can also build their own cookies and store data in them for later access.

How to Create a Cookie in PHP

PHP’s setcookie() method is used to create a new cookie. The general syntax for creating a cookie in PHP is as follows:

setcookie(name, value, expire, path, domain, secure, httponly);

The first parameter, name, is the only required one. The rest of the parameters are optional. Here is an example of creating a cookie:

setcookie("my_first_cookie","It contains a string");

How to get cookies and their value in PHP?

PHP stores cookies in the $_COOKIE global variable. To obtain a cookie and its value, simply provide the cookie’s name to the global variable. Here’s an example of utilizing the global variable to acquire a cookie:

$_COOKIE["my_first_cookie"] // will return "It contains a string"

How to delete cookies in PHP?

A cookie can be configured to expire after a certain period of time, after which it will be immediately destroyed. Here’s an example of generating a cookie with a one-day expiration time:

setcookie("my_first_cookie","It contains a string", time() + (86400), "/"); // 86400 = 1 day

Because the cookie’s expiration period must be in seconds, we used the time() method to return the current time and add the amount of seconds in a day (86400).

How to update cookies in PHP?

The same setcookie() function may be used to update a cookie. Simply invoke the function with the cookie’s name and set the new arguments. Here’s an example of changing the expiry period of a cookie to two days:

setcookie("my_first_cookie","It contains a string", time() + (86400 * 2), "/"); // 86400 = 1 day

It’s worth mentioning that cookies are automatically URL encoded when submitted in a request and decoded when received. The setrawcookie() function can be used to deactivate this.

You can also delete a cookie by updating its expiry time to a past date. Here’s an example of deleting a cookie immediately:

setcookie("my_first_cookie","", time() - 3600);

Does your browser allows cookies?

Here’s a simple way to check if your browser has enabled cookies:

if(count($_COOKIE) > 0) {
  echo "Cookies are enabled.";
} else {
  echo "Cookies are disabled.";
}

Understanding PHP Sessions

The HTTP protocol does not keep a user’s status on a webpage. Sessions are used to solve the challenge of persisting and accessing a variable across several web pages. In this part, we’ll look at how to use PHP sessions to store and access values.

Starting a Session

In PHP, use the session start() method to initiate a session. This method starts a new session or returns to an existing one. It is critical to notice that this function must be called before any output is transmitted to the browser; otherwise, an error will be generated. Here’s an example of how to begin a session:

<?php
session_start();

Storing Data

After starting a session, you may utilize the $_SESSION global variable to save data in the session. The data is saved as key-value pairs, where the key is the variable name and the value is the data to be recorded. Here’s an example of data storage in a session:

<?php
session_start();
$_SESSION['username'] = "JohnDoe";

Retrieving Data

To retrieve data from a session, you can use the $_SESSION global variable and access the key of the data that you want to retrieve. Here’s an example of retrieving data from a session:

<?php
session_start();
echo $_SESSION['username']; // will output "JohnDoe"

Deleting Data

To delete data from a session, you can unset the key of the data that you want to remove. Here’s an example of deleting data from a session:

<?php
session_start();
unset($_SESSION['username']);

Destroying a session

To destroy a session, you can use the session_destroy() function. This function will remove all data stored in the session and end the session. Here’s an example of destroying a session:

<?php
session_start();
session_destroy();

Q&A

What is the purpose of cookies in PHP?
Cookies are small files stored on the client’s computer that can contain information related to the user, request, response, and server. They are sent along with requests to the server, allowing the server to identify the user.

How can we create a cookie in PHP?
PHP’s setcookie() method is used to create a new cookie. It’s important to note that the first parameter, name, is the only required one, while the rest of the parameters are optional.

How can we get the value of a cookie in PHP?
Cookies are stored in the $_COOKIE global variable in PHP. To get a cookie and its value, you can simply pass the name of the cookie to the global variable.

How can we delete a cookie in PHP?
You can set an expiry time for a cookie, after which it will be automatically deleted. You can also update the expiry time of a cookie to a past date in order to delete it immediately.

What is the purpose of sessions in PHP?
Sessions are used to persist and access a value across multiple web pages.

Exercises:

  1. What is the difference between a session and a cookie?
  2. How do you start a session?
  3. How do you set a session variable?
  4. How do you destroy a session?
  5. How do you set a cookie?
  6. How do you retrieve the value of a cookie?
  7. How do you unset a cookie?

Answers:

  1. A session is a way to store data on the server, while a cookie is a way to store data on the client’s computer. Sessions are typically used for authentication and authorization, while cookies are used for user preferences and tracking.
  2. To start a session in PHP, use the session_start() function.
  3. To set a session variable in PHP, use the $_SESSION superglobal array, like so: $_SESSION[‘variable_name’] = ‘value’;
  4. To destroy a session in PHP, use the session_destroy() function.
  5. To set a cookie in PHP, use the setcookie() function, like so: setcookie(‘cookie_name’, ‘value’, time() + (86400 * 30), ‘/’);
  6. To retrieve the value of a cookie in PHP, use the $_COOKIE superglobal array, like so: echo $_COOKIE[‘cookie_name’];
  7. To unset a cookie in PHP, use the setcookie() function with an expiration date in the past, like so: setcookie(‘cookie_name’, ”, time() – 3600);
HTTP Request Methods in PHP
File Handling in PHP
en English
X
Scroll to Top