What are Cookies?
Cookies are those text segments that you can store on the user's computer, and PHP has good support for setting and reading cookies. Those segment of texts can persist even when the user's computer is switched off, so you can store information about user easily. That's great when you customize a web application- the user might choose a color scheme, for example. Cookies are used for all kinds of purposes from the benign to the more sinister-such as tracking what ads user has seen already and responded to. Setting and reading cookies in php is not hard!
How to set a Cookie?
You set the cookie on the user's machine with the PHP and the setcookie function:
set cookie(name [, value [, expire [, path [, domain [, secure ]]]]] )Now let's see what these parameters really mean:
- name : The name of the Cookie!
- value : The value of the Cookie. (This value is stored in the clients computer, so don't store sensitive information.)
- expire : The time of the Cookie expires. This is the number of seconds since January 1, 1970. You will most likely set this with PHP time function plus the number of seconds before you want it to explore.
- path : The path on the server on which the Cookie will be available on.
- domain : The domain for which the Cookie is available.
- secure : Indicates that the Cookie should only be transmitted over a secure HTTPS connection. When set to 1, the cookie will only be set if a secure connection exists. The default is 0.
Now some simple steps to create a Cookie!
In this example I am gonna create a PHP document name as phpsetcookie.php (You can choose any random name for you php file!)
- Now just observe the code written, because this is the code which you need to create a new random Cookie.
- Our PHP code to create Cookie is going to be:
<?php setcookie("message", "No worries."); ?>Now let's frame this in our document!
<html>
<head>
<title> Setting a Cookie </title>
<?php setcookie("message", "No worries."); ?>
</head>
<body>
<h1>Setting a Cookie</h1>
The Cookie was set
<body>
</html>
Your browser should such a message (see the pic below!)
Short and Good, thanks alot, this makes this Tutorial a lot easy!
ReplyDeleteThanks! IF you need help about anything in basic PHP then just mail me a request at teejhiab@gmail.com
Delete