Delete a variable or a cookie

It’s not the same to delete a cookie file completely from the user's disk, that simply empty the value of some of its variables.

Delete a variable or a cookie | Learn PHP & MySQL | It’s not the same to delete a cookie file completely from the user's disk, that simply empty the value of some of its variables

It is not the same to delete a cookie file completely from the user's disk, than simply to empty the value of some of its variables.

The way to empty the value of a cookie variable is very simple, and consists of defining it as if we were creating it, but without specifying any value:

<?php
setcookie("name");
?>

Of all the possible parameters that we can provide within the parentheses when creating a cookie, the only mandatory is the name of the variable and, in the case of being the only one that we provide, it produces the emptying of the data that we had stored previously in that variable.

With the same logic as in the case of creating a cookie, if after ordering to delete a cookie, in the same code of the same page that is running on the server we try to read that cookie, it will still exist, since only in the The next request to the server will no longer be available.

In addition, if we want to delete a previously read cookie variable from the server, it will be necessary to use the unset function:

<?php
unset ($_COOKIE["name"];
?>

This not only empties the value of the variable, but eliminates the variable itself.

Instead, to completely remove the cookie file from the user's disk, it will be necessary to use an extra argument from the setcookie function, which we learn below.

Optional arguments

We have already used in the different examples several of the arguments or parameters that we can use within the parentheses of the setcookie function.

The totality of these arguments is the following:

setcookie (name, value, duration, path, domain, security)

The only mandatory parameter is the name of the cookie or variable (which if used without any other data, causes the deletion of that cookie variable, as we have just learned).

If using this function we want to skip (omit) one of the arguments and then specify another, we must also complete its position with "" (nothing, not even a space, in quotes), except in the case of duration or expiration, which must be completed with a 0, and except also the last one and the arguments, that of limiting the cookie that will be transmitted only under an https (secure) connection, in which the possible values of that argument are 1 (it is obliged to transmit it by https ) or 0 (https is not necessary).

Let's see, then, the possible arguments that we have not yet seen, such as the route and the domain.

This not only empties the value of the variable, but eliminates the variable itself.

Instead, to completely remove the cookie file from the user's disk, it will be necessary to use an extra argument from the setcookie function, which we learn below.

Optional arguments

We have already used in the different examples several of the arguments or parameters that we can use within the parentheses of the setcookie function.

The totality of these arguments is the following:

setcookie (name, value, duration, path, domain, security)

The only mandatory parameter is the name of the cookie or variable (which if used without any other data, causes the deletion of that cookie variable, as we have just learned).

If using this function we want to skip (omit) one of the arguments and then specify another, we must also complete its position with "" (nothing, not even a space, in quotes), except in the case of duration or expiration, which must be completed with a 0, and except also the last one and the arguments, that of limiting the cookie that will be transmitted only under an https (secure) connection, in which the possible values of that argument are 1 (it is obliged to transmit it by https ) or 0 (https is not necessary).

Let's see, then, the possible arguments that we have not yet seen, such as the route and the domain.

The fourth argument of the function that creates a cookie, the route, indicates from which directory (folder) from a server will access the data of that cookie, preventing the reading of your data to any PHP page that is not stored within that binder.

An example:

<?php
setcookie ("test",$ value, time ()+3600, "forum/ "," ",1);
?>

We are defining a series of things:

  • We create a variable called "test"
  • Its content is whatever it was stored in the variable "$value",
  • This data will cease to exist one hour after its creation (60 minutes * 60 seconds = 3600 seconds)
  • This "test" variable can only be read from PHP pages that are stored within the "forum" folder of our site
  • We do not specify any subdomain, leaving the quotes empty
  • and we force to use a secure server (https) to transmit the variable (therefore, the cookie will not be created if we do not have an https server)

The fifth argument, that of the domain, specifies from which domain the cookie will be accessed (this is used for submines of the same site, so that only from that subdomain can the data of the cookies be read).

Another example:

<?php
setcookie("login", $data, time () + (60 * 60 *24) , " "," us.un dominio.com",0);
?>

In this case, the cookie will last 24 hours, and can only be read from any subdomain folder ar within the undominio.com domain that was specified, without a secure connection being necessary to send the data.

And finally, if we want to eliminate a cookie completely, emptying the value of its variable and physically deleting the file from the user's disk, the way to do it is indicating a time of expiration before the current one (in the following example, the " zero "of the third argument):

<?php servidor
setcookie("name", $data,0);
?>

Let us bear in mind, then, that there are three different tools to "eliminate data related to cookies, but they are not the same:

  1. Empty a cookie variable without deleting it, with setcookie without value
  2. Remove from a variable already read with unset
  3. Delete the physical file from the user's disk with setcookie and previous date

Let's now look at a somewhat more complex, but complete and ready to use, example of using cookies to generate custom HTML code.

In this case, the goal will be to generate just one word that will be written with a PHP echo within the <link> tag of the pages of our site:

<link rel ="stylesheet" type ="text/ css " href ="xxxx.css" />

Therefore, depending on the value of that word, it will be a different style sheet that the browser will apply to that user while navigating through that site (which will allow to offer some personalized design options to each user, for example, choose different font sizes, number of columns to choose, colors and images of personalized backgrounds, etc. All this, simply choosing which style sheet will be applied, which will be decided by the value stored in a cookie).

The sequence of steps will be this:

  1. We will verify if the user has just chosen a style through a selection menu
  2. (We verify if in $ _POST there exists the variable that gives name to the select that we provided to choose styles);
  3. if you did, we will store in a cookie the name of the chosen style, and we will also write it in <link>;
  4. otherwise, if $ _POST did not provide anything, we verified with another conditional if it already has the cookie stored before, reading it from $ _COOKIE and, in that case, we will read the variable that was provided by that cookie and we will write its value within the <link> tag;
  5. and, finally, if not in $ _COOKIE we find data, it is that the user arrives at the page for the first time and still did not choose anything, so, in that case, we will write a default value within the <link>

Let's do it! We will create a file named page.php:

<?php
if(isset($_POST ["election"]) ) {
// if the data is located there, it is that they just used the form and sent a chosen style
$sheet=$_POST["elección"];
// entonces, dejamos preparada una variable para usarla dentro de <link>
setcookie ("chosen",$sheet,time () + (60 * 60 * 24 *30) ) ;
// and we save a variable that we call "chosen" within a cookie; its value is taken from $ _POST ["election" (or $ sheet that is the same thing), and we define its expiration for three days
} else {
//if we do not find the data in $ _POST, we see if it was already in a cookie from a previous visit:
if(isset($_COOKIE["chosen"])) {
//if it is, we put in the same variable $ sheet what the user had chosen:
$sheet=$_COOKIE["choice"];
} else {
//if it was not there either, we will show a default sheet:
$sheet="sheet-by-default";
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C// DTD XHTML 1.0 Strict // EN"
"http: //www.org / TR/xhtm11/ DTD/ xhtm11 – strict.dtd">
<html xmlns = "http: // www.w3.org/1999/xhtml">
<head><title> using cookies to choose a style sheet </title>
<meta http-equiv="content-Type" content = "text/html; charset = utf-8" />
<?php
// whatever the path taken previously, the variable $ sheet must have some value, so we read it and use it to load the respective sheet:
if(isset($sheet) ) {
echo '<link rel = "stylesheet" type = "text / css" href= " '.$sheet. ' . css" />
}
?>
</head>
<body>
<h1>Let's choose a design<h1/>
<form action= "página.php " method = "post " >
<fieldset>
<p>Let's change the style to our liking</p>
<select name = "choice ">
<option value ="minimalist"> Minimalist</option>
<option value ="old"> Old</option>
<option value ="modern">Modern</option>
<option value ="zoom"> Large fonts</option>
<option value ="three">Three colums</option>
<option value ="two">Two columns</option>
</select>
<input type="submit" value="Choose" />
</fieldset>
</form>
</body>
</html>

For the puzzle to work, the names we will give to our style sheets will be what we have been in this code: "sheet by default.css", "minimalist.css", "ancient.css", "modern. css "," zoom.css "," three.css "and" dos.css".

Of course, let's make the design changes in the different CSS sheets noticeable, so that when navigating through the different pages of our site, we will see how the chosen style is maintained at the beginning of the navigation.

Add on each page of our site the contents of each page, and include a menu to navigate between them, and make sure to repeat both the selection menu to choose a style, and the necessary PHP code to detect it and save it in cookies or read them on them, completing the <link> tag.

Ideas to apply cookies

To finish with the topic of cookies, we will suggest some ideas for other uses than those we have already seen.

For example, we could memorize if a user has already visited a product or category of products in a catalog. If, thanks to a cookie, we detect that you have already visited the product "Ping pong table", then we could show you an advertisement for Ping Pallets "or" ping pong classes at home. "Tailored content …

Another interesting use was to detect which of our visitors had previously entered a page of a registration or contact form, but without using it (having loaded it into a cookie a special value when arriving at the reception page of the form), and show them a special content that the "anime" to complete the query or registration that they did not decide to specify in their previous visit.

Similarly, in a site that sells a product (ecommerce) through a shopping cart, we could detect if someone is using the cookie (that is, if you have already chosen products, that is, you are interested in some of them), but not finalize the purchase, and show a specific text (as in the previous case, on the purchase completion page we should modify or delete the previous cookie of the cart, so that it is no longer shown that text).

And, in addition, if someone "yes" bought a product or service, at the time of purchase, we could store a cookie so that in a certain number of days later (which will depend on the duration of the product sold), upon entering our site, we remind you that your product is about to end and that it is time for you to buy it again.

In sites that publish content with certain frequency (daily, weekly, monthly) we could save the date of the last visit of the user to our site and, calculating the difference between the current date and the last visit, show a poster of "new content! " in the links that point to content published after your last visit (very soon we will learn to handle functions for calculations with date that will allow us to do this kind of thing)

There are really many applications that can occur through the use of cookies. But, always within the topic of identification of the user, it is possible to go one level further, and start working with sessions, which is the topic that we will see next.

🤖

ChatGPT Free
Ask questions on any topic

CITE ARTICLE


For homework, research, thesis, books, magazines, blogs or academic articles

APA Format Reference:

Delgado, Hugo. (2019).
Delete a variable or a cookie.
Retrieved Nov 04, 2024, from
https://disenowebakus.net/en/delete-variable-cookie-php

Participates!

Share it with your friends in Social Networks!

Professor at the University of Guadalajara

Hugo Delgado Desarrollador y Diseñador Web en Puerto Vallarta

Professional in Web Development and SEO Positioning for more than 10 continuous years.
We have more than 200 certificates and recognitions in the Academic and Professional trajectory, including diploma certificates certified by Google.

CONTINUE LEARNING

IT ALSO DESERVES TO PAY TO VISIT:

Not finding what you need?

Use our internal search to discover more information
Related content:

Would you like to learn more about Web Design?

Meet all the courses and tutorials that we have for you completely free
Learn Web Design
 

Leave your Comment

SPONSOR

Your business can also appear here. More information