PHP Cookie

PHP cookies tutorial will explain you How to set or destroy cookies in PHP? with example.

PHP Cookies are simple text strings. PHP Cookies are stored on the client’s machine and not on the server.

What is a PHP cookie?
PHP Cookie is usually a small piece of data sent from a website and stored in an user’s web browser while an user is browsing a website. One simple route to maintain data between the diverse pages in a web application is with PHP cookies.

Creating first PHP cookie

We will be using the PHP setcookie() function provided to set cookies.

Syntax for PHP setcookie() function:

This will create cookies called name with the value value. The other parameters are all optional. The expire field sets a date beyond which the cookie is no longer relevant. (Note that if no expiry date is set, PHP cookies is effectively permanent unless manually deleted by you or other user.)

Together the path and domain can be used to specify the URL or URLs for which the cookie is relevant. The secure keyword means that the cookies will not sent over a plain HTTP connection.

Example on PHP Cookies:

In this example we will be creating PHP cookie that stores the user’s last visit to measure how often people return to visit our webpage. We want to ignore people that take longer than two months to return to the site, so we will set the cookie’s expiration date to two months in the future!

Retrieving Fresh PHP cookie

If PHP cookie hasn’t expired yet, let’s retrieve it from the user’s PC using $_COOKIE associative array.

Example for retrieving PHP cookie:

In this script first uses the isset function to be sure that our “lastVisit” cookies still exists on the user’s PC, if it does, then the user’s last visit is displayed.

Deleting cookie

It is good to delete a cookie manually from your site. All you do is set the same cookie but with no value and with an expiry date in the past. This forces the browser to delete the cookie from the users system.

 Delete lastVisit cookie from the users system:

As shown, the value is empty and the expiry date is the current time() minus 60000 seconds, Any negative number will work but due to variations in computer times, it is not recommended to use -1 but instead something higher like a day or two.

SHARE
Previous articlePHP File Upload
Next articlePHP Session
I am a young Information Systems Security Engineer(CEH). I had started with penetration testing when i am 17 years old. It all started with Kali linux and Metasploit.In free time i will play with Security holes/Bug bounty/Pentesting and Hacking !!!