As an open source content management system, WordPress is today one of the major platforms for sites and blogs of any kind. In comparison to most conventional CMS platforms, WordPress is quite stateless thus the need of sessions and cookies to maintain state. When you’re trying to create a simple website on top of WordPress, you will need some kind of structure to retain your sessions. 

A quick outline on what we will address is that, cookies offer an easy and standard method for handling various settings for users who have logged in when they want to access a site. On the other hand, sessions mostly use cookies, but provide more usability and security properties.

Most of the data they retain include anything from your login details to the things you have browsed, articles you’ve read, products you have ordered and more. This way they are able to provide a personalised user search experience without putting the user’s data at risk. Through application of sessions and cookies, we can preserve the state of WordPress, moreso the storing of user information can be addressed, and applications can be more adjusted to the user.

Here, we’ll start by explaining what cookies and sessions are used for in WordPress as well as how website owners can thrive through them. Everybody enjoys regular offline cookies although the interactive use on websites around the internet is still a subject of misunderstanding.

Table of Contents

What are Cookies

What are PHP Sessions

Why do i need to use cookies and retain sessions

An Overview of Cookies

A PHP Session Overview

Issues with Cookies and PHP Sessions

Cookies alternatives

PHP Sessions Solutions

How to render a cookie consent on WordPress

Final Thoughts

What are Cookies

Cookies are simple text scripts, often encrypted, which are formed and retained in the user’s browser while they access the website. Once the user clicks on the page again, the cookie will be sent back to the browser and reminds the user of the former activities. For instance, if a website you regularly use retains your login details, you do not need to re-authenticate yourself every time this happens. If you search for products online, cookies will assist the website to display to you the products you are most likely to purchase.

What are PHP Sessions

A PHP session is still a cookie, which serves as a digital identity for a user or at every point a guest visits the site. Sometimes known as PHPSESSID or a session cookie, it is usually located in the / tmp / directory on the web server as a whole. It’s used in setting up a user session and passing of state information via a temporary cookie. Anytime you access a webpage, you are given one from the period of your stay which will be used to recognise you through your time on the internet. A PHP session normally ends once the user has closed his or her web browser.

Why do I need to use cookies and retain sessions?

Latest advances in content marketing, development in hacking, and digital marketing in general make it easier for websites to install cookies that serve like a marker which could be used to store and even transfer user interaction through sites. Cookies are an important element of the Web. Without them, websites will become less functional and interactive. They offer websites the potential to understand and strengthen themselves.

Below are amongst some of the widely known uses of cookies on numerous websites:

  • Store and handle user login credentials  
  • Retain temporary session info after a visitor has accessed a site 
  • Ecommerce sites stores cookies to identify cart products after every user visits 
  • Monitor user interaction on the website and provide customized customer experience.
  • In case you’re into reading news online, the website may just store your IP information to bring you news focused on your location.

PHP session normally requires more space than cookies. Session information is saved inside a temporary folder or database on a web server as mentioned earlier.

For PHP, a session should take care of the below specific tasks: 

  • Session monitoring information 
  • Retaining session-related information.

An Overview of Cookies

By default, WordPress uses cookies to handle logged-in user sessions and authentication.  Other third party services like google adsense being used in your website may also set cookies whereas various plugins come with their cookies set on board.
To check and monitor cookies in your web browser, for instance in chrome, head to Settings and then select Show Advanced Settings … under the “Privacy” part, select Content/Site Settings. A modal page should show you suggestions on how you choose to store cookies for your website. You can leave it as it is on default and proceed to all cookies and site data. The next screen should show the cookies that your browser has been storing once you click on “see all cookies and site data”.

Cookies and Sessions

How To Set Cookies in WordPress

To keep things easy to implement you should know that the cookies are set using code manipulation in WordPress by scripting it in PHP. The code in PHP is to be added to the functions.php file in the active theme’s directory which can be accessed through Cpanel or FTP method or from your WordPress appearance section under theme editor.

In order to set cookies we use the function setcookie() which takes various types of elements that include:

  • Cookie name Cookie value 
  • Path (Optional, defaults to Root path of the site) 
  • Domain (Optional, defaults to the domain of your website)
  • Expiration (Optional: sets the time limit after the cookie expires) 
  • Secure (Optional, If valid, only transfers cookie data via HTTPS) 
  • Http only (Optional, when set true the cookie is only available via HTTP and can not be accessed by scripts)

Therefore, the setcookie() function is very well straightforward. The syntax is as follows:

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

For example, in case you want to store the username of your user, you should add this code snippet to the functions.php file:


<?php
add_action( 'init', 'setting_my_first_cookie' );
function setting_my_first_cookie() {
setcookie( $v_username, $v_value, 30 * DAY_IN_SECONDS, COOKIEPATH, COOKIE_DOMAIN );
}
?>

You can notice that the time value is set for thirty days which basically shows that the cookie will expire thirty days after it’s created. The DAYS_IN_SECONDS value is a constant provided by WordPress, whereas as mentioned above the last two cookie parameters are set by WordPress by default. In other cases some WordPress developers opt to set the expiration time based on user input. In this case a user input could be referred to as the number of days. In some sites you may come across “Remember me for X days” of which is the same concept applied.

Getting Cookies in WordPress

After you have created cookies in your website, you will need to recall information previously collected from the visitors, once they return to your website. To achieve this we use the $COOKIE function to fetch the cookie we created in the above code. This function is an associative array that can be used to connect to the cookie that we create.

To avoid any unwanted errors, you really need to use the isset() function to assess whether the cookie has any value in it, that is whether it has been set or not by returning a true or a false. When the cookie is set, it’s necessary to echo the value which is to be retrieved in order to show it.

<?php

    if( ! isset( $_COOKIE[$visitor_username] ) ) {
    echo "The cookie: '" . $visitor_username . "' is not set.";
    } else {
    echo "The cookie '" . $visitor_username . "' is set.";
    echo "Value of cookie: " . $_COOKIE[$visitor_username];
    }
?>

This implies that once we have retrieved the cookie, the value is decoded by default and similarly when the cookie was set earlier and sent to the HTTP header the value is automatically url encoded.

Deleting Cookies in WordPress

Usually, if you don’t like a certain set of information anymore, you really consider deleting it. Moreso, cookies do expire with time depending on the values you set and it’s likely that you may not need them anymore. You do not need a unique function to delete a cookie. Instead, we just reverse the setting function. For this syntax, we use the same function which was used to set it  in order to delete it. In other words, you will have to use the following code, which is again added in the function.php file of your theme:


<?php
 setcookie( $v_username, '', time() - ( 15 * 60 ) );
?>

The cookie must be pushed to expire by changing its value parameter to a null value and sending a period stamp that was in the prior (time() – (15 * 60)).

A PHP Session Overview

The primary goal of PHP Sessions is to create a state connection between the website and remote users, with the potential to store information via consequent client interactions.

Most websites opt to just use PHP sessions instead of cookies. This is because cookies aren’t really that secure since they are retained in the browser of the recipient. This implies that it is easy for someone to open the cookie file and read or change the information contained within it.

Starting/creating a php session

Throughout a session-based setting, each user is recognized by a specific number known as a session identifier, and this specific number is used to connect each user to its server information.

The function session_start() is implemented to initiate a session environment. The Session variable often operates by its own setting or its corresponding setting 

Note: session_start() must be used between the php tags

add_action('init', 'start_session', 1);
function start_session() {
  if(!session_id()) {
    session_start();
  }
}

Ending a PHP session

PHP provides an automated function called session destroy that manages the removal of all session information. However, it can be challenging when to call this function based on the request. WordPress often offers us with a few options to do exactly that in the API Actions. 

In WordPress, we would have to delete the session until the user logs out or the new user logs into the site. We will use two actions offered which are, wp_logout and wp_login, to invoke a function that we shall develop called end session. Finally an end session function is created to destroy the whole session. Below is a code that illustrates this:

add_action('wp_logout','end_session');
add_action('wp_login','end_session');
function end_session() {
session_destroy ();
}

A custom hook could be implemented to terminate a session somewhere within the theme by use of the do_action function given by WordPress to call the end session function we defined above.

Then we can apply the below code to the functions.php file in the theme editor

add_action('end_session_action', 'end_session');
do_action('end_session_action');

A global $_SESSION variable can be added which can be accessed at a given point in the website when the user is browsing or in a user session. This can be achieved by accessing the $_SESSION variable which is an array type. The following is an example of adding data to the session array.

$foo = 'Foo Data';
$_SESSION['foo'] = $foo;

Issues with cookies and PHP Sessions

If active, the cookies normally function with PHP while the page is loaded to perform a special operation. Once the site is served from cache, it means it had already been generated before by the server. In case the page is being cached, the cookie can not be developed and execute the intended action while loading the page as intended.

A cookie can only function as intended when logging in to the WordPress Admin Dashboard. This is as a result of when logged-in user sessions explicitly override the page cache level and can be accessed by PHP at any time. For more clarity on this, storing new cookies to the server is very much possible. However, the HTTP $COOKIES object will not depict such improvements as the server is not checking for improvements: it contains a cached version of this whole site page, including the headers.

PHP sessions do pose the main challenge due to the special user Identifiers. Specific IDs essentially break the cache and force each session not to be cached. This will trigger significant performance problems on your website. Having this in mind, most solutions provided will ignore the headers which are meant to define a PHPSESSID cookie.

As mentioned earlier, PHP Sessions do retain data within a file server into their own directory. Writing data to a file is an I / O operation that is used to back up and generate heavy server loads. Moreso, in case the website is on a distributed AWS consisting of various web servers, this kind of session storage does not function.

Cookies and Session Alternatives For WordPress

When you choose to use PHP to read cookies, it could possibly just produce an empty cookie set. However, this is not considered to be ideal but at the same time, cookies are considered to be a requirement for websites . Web caching may not necessarily imply that you can not use PHP to read cookies. Here are two solutions to this:

Admin Ajax Implementation

AJax is indeed a means to interact directly to your web server after loading the website — and then change your page depending on the outcome of your interaction. It’s exactly what is required to get beyond a full-page cache, Therefore this issue is as follows: the newest cookie information is stored on the server, but the server doesn’t check for it as it produces the page hence the need to get into the server and obtain the information using Ajax.

Use JavaScript

JS simply triggers an admin-ajax.php POST query. PHP will then be able to accept and, if necessary, execute various actions. Basically, you have HTML placeholders and use JavaScript to pull in info over an API or ajax call.

When Cookies are present Exclude Pages From Cache

We normally advocate this especially for users  running extremely interactive sites like those of WooCommerce and Easy Digital Downloads. Moreso, uncached pages do not cope well with traffic.

PHP Sessions Solution For WordPress

WordPress does not explicitly use PHP sessions on its own. The best way to store session information is by using the database. When you’re searching through the code of your site to identify a plugin or theme file that uses session start function, look if there is any upgrade available. Check the code again after upgrading to ensure that it has been corrected. If your plugin or theme has no update or keeps using sessions following the initial upgrade, we strongly suggest contacting the developer or seeking a rather more safe solution.

How to render cookie Consent in WordPress

The new data privacy laws such as GDPR, ePR and CCPA require that all websites are mandated to display a cookie’s consent within their website. This is because as stated earlier cookies are prone  to WordPress users collecting visitors information and are sharable to other third party platforms. On the other hand, when you are using cookies that require the user’s approval, things may get a bit tricky. This could be because your site can only insert and store such cookies once the visitors have offered their permission to do so.

To display a Cookie Approval Notice in WordPress the very first step you have to do is install and activate our recommended cookie plugin which in this case is  GDPR Cookie Consent .

This plugin does indicate a notification for the visitors to Accept or Reject choices of storing cookies and obtaining data. By default, the cookie value is normally and should be set to “Null.” More so  the admin could insert cookie information to the backend. One could also implement a shortcode to show a list of cookies in the policy page section.
Here are some of the best features of the plugin:

  • Fully customisable features
  • Cookie Audit shortcode
  • WPML compatible
  • qTranslate support
  • Amazingly responsive
  • Put the cookie bar in either the header or the footer
  • accept cookie policy on scroll

Final Thoughts

Cookies are really crucial in keeping most websites running, and even though you may not want to get your hands dirty by actively scripting them, it’s helpful to have some insight about how they function. You may not want to use sessions when you are creating a flexible or load stabilized website. 

HTTP is stateless and PHP SESSIONS are state-driven. Sessions are retained and managed by the server. 

The deployment of cookies and PHP sessions in WordPress is convenient for someone who knows the fundamentals of PHP – and for those who don’t, now they have learnt something new!

Contributor
No Comments
Comments to: Cookies and PHP Sessions in WordPress

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

    This site uses Akismet to reduce spam. Learn how your comment data is processed.

    Privacy Preference Center

    Functionality

    We use third-party analytics services to help understand your usage of our services. In particular, we provide a limited amount of your information (such as sign-up date and some personal information like your email address) to 3rd party service and utilize it to collect data for analytics purposes when you visit our website or use our product.

    __cfduid,intercom-id-*, intercom-lou-*, intercom-lou-*, intercom-session-*, intercom-session-*, intercom-visitor-session-*

    Performance

    These cookies allow us to count visits and traffic sources so we can measure and improve the performance of our site. They help us to know which pages are the most and least popular and see how visitors move around the site.

    All information these cookies collect is aggregated and therefore anonymous. If you do not allow these cookies we will not know when you have visited our site, and will not be able to monitor its performance.

    _ga, _gat_gtag_UA_106868094_1, _gid
    IDE
    AID
    NID,1P_JAR

    Advertising

    Necessary

    These cookies are necessary for the website to function and cannot be turned off. They are usually only set in response to actions made by you which amount to a request for services, such as setting your privacy preferences, logging in or filling in forms.

    You can set your browser to block or alert you about these cookies, but some parts of the site will not then work. These cookies do not store any personally identifiable information.

    PHPSESSID, wordpress_logged_in_*, wordpress_sec_*, wp-settings-time-1, gdpr[privacy_bar], gdpr[allowed_cookies], gdpr[consent_types]