PHP Tutorial #02 Cookies ( Create, Update and Delete )

in #utopian-io5 years ago (edited)

Image Source

Repository

https://github.com/php/php-src

What Will I Learn?

  • You will learn how to create a cookie.
  • You will learn how to modify a cookie.
  • You will learn how to delete a cookie.

Requirements

  • Text Editor.
  • Server support PHP.
  • Browser.

Difficulty

  • Basic

Tutorial Contents

The Cookies are used to register a user's data in the site, there are several ways to use cookies :

  • To not ask each time the user to enter his username.
  • To prevent the redundancy, for example if there is a form that asks the user to enter his age, it is not necessary to ask again the age in another form, the correct method is to register it in the database or by the Cookies.
The cookies were created by Netscape to extend the functionality of the HTTP protocol and to add the ability to link the different requests. 
They were subsequently integrated into the protocol, all current browsers support cookies.

1- Introduction

The Cookies are small ' txt ' files created by the browser whatever (Chrome, Firefox ..etc) in the PC of the user at the request of the server or the execution of certain code in the site ( Creation of Cookie ).

Cookies present an identity card of the user (his username, age, id ... etc), with this card the site and the pages can identify the user easily.

When the client sends a request to the server, the server repeats with the page and the cookie if it is identified, and this permutation of data is through the HTTP protocol.

When you send a cookie, you ask the browser to send it back in future requests. However, he has the option to refuse and not to do so. Most browsers have an option to refuse cookies.

In some browsers, you must check the cookie storage configuration to execute and manipulate the site correctly.

The Cookies are two types, there are cookies with expiration date and cookies without expiration date.

If the client has sent a cookie with an expiration date, the stored file will be in RAM , the opposite if the client has given a lifetime, the file will be in the hard disk.

The creation, modification and deletion of cookies is done by a single function that is 'setCookie ()', it is the function that handles all operations. It accepts at least two parameters (the cookie name and the value).

2- Create Cookie

PHP allows you to fully manage the sending and receiving of cookies via the setcookie() function.

To avoid all the problems of (read / write), this function must be used at the top of your entire page, because the web server sends all the headers as soon as it receives text to be displayed by the user script.

Now in the user's computer and in the stored file there is the cookie 'username' and its value 'Alex', this information will be stored in an array that the developer can manipulate using the superglobal variable '$_COOKIE ', the content of this variable is an array (associative array) whose key is the name of the cookie and the value is the cookie value.

To access the cookie value is by using $_COOKIE['cookie name'], and as it's an array to get the value the ' [ ] ' is used.

There is an example for authentication, so the user will enter his username and the site will create a cookie with this username, here is the code.


// Create Cookie
echo "Welcome " . $_POST['username'];
setCookie('username', $_POST['username']);
header( "refresh:3;url=displayCookie.php" );
// Print Value Of Cookie
echo "In the page ' displayCookie ' the username is ' . $_COOKIE['username'];

The page ' test.php' contains the ' form ' that will send the data to ' createCookie.php ' page, in this page the cookie will be created using the ' setcookie() ' function.

This function accepts 7 parameters : name,value, expire, path, domaine, secure and httponly.

This image from the w3school, they gave the parameter and its definition.

The first cookie created in this example without expiry date, now let's create another cookie with the rest of parameters.


echo "Welcome " . $_POST['username'];
setCookie('username', $_POST['username'], time()+3600,"/");
header( "refresh:3;url=displayCookie.php" );
// Print Value Of Cookie
echo "In the page ' displayCookie ' the username is ' . $_COOKIE['username'];

The same code and the same order, the only difference is the setcookie function, so in this example the setcookie with the other parameters and that's the result

3- Modify Cookie

In several sites there is the option to modify the profile of a user, if the user first authenticated by ' username1 ' and he changes his username to ' username2 ', for that the cookie must be changed.

This modification is done by the setcookie() function, it is necessary to keep the same name and to change the other parameters like value ..etc.

To complete the example above when the user authenticates he will find a form to change his username if he wants, when he changes the username the cookie will be changed and that's the code


setCookie('username', $_POST['username']); // setcookie to change the username of the user passed from the form of displayCookie.php
echo "You have changed your username to : " . $_COOKIE['username']; // print the new username ( new cookie )

4- Delete Cookie

Like creation and modification, there is also the deletion of cookie, then the term management that we already mentioned in the introduction part means (Creation, Modification and Suppression).

To delete a cookie there are several methods, the most known method is to empty the values of a cookie, how?

The 'setcookie ()' function accepts 7 parameters, to empty it you have to keep the name and delete the other parameters like that


// Two methods
setcookie('username'); // name without the other parameters ( method 1 )
?>

The second method is to change the expiration date, logically the expiry date is bigger then the creation date but to delete a cookie you have to change the expiration date to be less then the creation date, here is the method


setCookie('username', 'Alex', time() - 3600 ); // change the expiry date less then the creation date ( method 2)
echo "After deletion the username is " . $_COOKIE['username']; // print the new username ( new cookie )

Curriculum

Part1

Proof of Work Done

 https://github.com/alex-harry/phpTutorial/blob/master/all.php 

Sort:  

Thank you for your contribution @alex-harry.
We have been analyzing your tutorial and we suggest the following points:

  • Your contribution is well structured and well explained.

  • The subject of cookies in the PHP programming language already exists on the internet with many tutorials explaining how to use it.

  • At Utopian it's very important to bring innovative content to the open source community to learn more.

Looking forward to your upcoming tutorials.

Your contribution has been evaluated according to Utopian policies and guidelines, as well as a predefined set of questions pertaining to the category.

To view those questions and the relevant answers related to your post, click here.


Need help? Chat with us on Discord.

[utopian-moderator]

Hey, @alex-harry!

Thanks for contributing on Utopian.
We’re already looking forward to your next contribution!

Get higher incentives and support Utopian.io!
Simply set @utopian.pay as a 5% (or higher) payout beneficiary on your contribution post (via SteemPlus or Steeditor).

Want to chat? Join us on Discord https://discord.gg/h52nFrV.

Vote for Utopian Witness!

#utopian-io has been a gift. We would like to keep its curation-efforts alive here on 'marlians.com'. We want to curate and reward 'contributions to open-source projects' with MARLIANS on the the marlians.com tribe, a SCOT-enabled steem condenser. Contributions can include suggestions, graphics, bug-finds, code etc. You can simply add in #marlians to your #utopian-io posts and it will appear on https://www.marlians.com/created/utopian enabling you to earn some MARLIANS along with steem/sbd. You can also post directly to steem via 'marlians.com'. We have some overseers who curate and who can render you help too. You can find them enlisted on https://www.marlians.com/created/utopian

Coin Marketplace

STEEM 0.20
TRX 0.25
JST 0.038
BTC 97272.68
ETH 3373.70
USDT 1.00
SBD 3.13