PHP Cookies Tutorial Online | Setcookie Function
×

PHP Cookies

4591

Cookies are kinds of text files, which are stored on the client computer and generally they are used for tracking purposes. PHP apparently supports to the HTTP cookies.

PHP offered a setcookie() function which helps to set a cookie. This function needs up to six arguments and should be called before the <html> tag.

For each cookie this PHP function has to be called independently.

See the format of setcookie function below:

setcookie(name, value, expire, path, domain, security);

- A 'cookie' is a piece of data stored on the client side.

- A 'cookie' is a small file that the server embeds on the user' computer.

- It is often used to identify a user.

A cookie is created with 'setcookie'.

Let's start the cookie:

<?php

$cookie_name="user";
$cookie_value="Vihaan";
// Here 'user' is the name of cookie and 'Vihaan' is the value of cookie.
setcookie($cookie_name,$cookie_value);

?>

You can also use 'time' to set the expiration for the cookie...

For Example:

<?php

$cookie_name="user";
$cookie_value="Vihaan";
$time="86400*30";
setcookie($cookie_name, $cookie_value, time() + $time);
// the number used here: 86400 are in seconds which means 24 Hours or 'a day' and 30 is used to define the number of days means '30 days'

?>

Notice that 'name' is required, other parameter optional like value, time etc. to set a cookie.

<?php

$cookie_name="user";
$cookie_value="Vihaan";
$time="86400*30";
setcookie($cookie_name, $cookie_value, time() + $time);
// the number used here: 86400 are in seconds which means 24 Hours or 'a day' and 30 is used to define the number of days means '30 days'

?>

Let see the brief information of all the arguments -

  • Name - This argument helps to set the name of the cookie and is saved in an environment variable known as HTTP_COOKIE_VARS. The name is used when accessing the cookies.
  • Value - It sets the value of the named variable and is the content that you really like to save.
  • Expiry - It specifies a future time in the seconds since 00:00:00 GMT on 1st Jan 1970. After this time, cookie will become unapproachable. If this parameter is not placed, then the cookie will automatically run out when the Web Browser is stopped up.
  • Path - It specifies the indexes for which the cookie is applicable. A single forward slash character shows the cookie to be valid for all the indexes.
  • Domain - This argument can be used to define the domain name in very large domains and must include at least two periods to be valid. All the cookies are only valid for the domain and host, which generated them.
  • Security - This can be locate to 1 to define that the cookie should only be sent by safe transmission using the HTTPS otherwise fix to 0 which mean cookie can be sent by usual HTTP.


Best WordPress Hosting


Share:


Discount Coupons

Get a .COM for just $6.98

Secure Domain for a Mini Price



Leave a Reply


Comments
    Waiting for your comments