PHP Cookies are stored on the client side. PHP cookies are not as secure as sessions.please use sessions as much as possible instead of cookie.
PHP cookie is a small piece of information which is stored at client browser. It is used to recognize the user.
Cookie is created at server side and saved to client browser.
There are three steps occurred in cookie to users details.
- PHP Server script sends a set of cookies to the browser like name, age, address , or phone number etc.
- Browser stores this information on local computer machine for future use.
- When next time browser sends any request to web server then it sends those cookies information to the server and server uses that information to identify the user.
How to Create Cookies with PHP?
setcookie() function is used to create cookie.
setcookie(name, value, expire, path, domain, security);
This function is used to store value to variable.
- Name − This sets the name of the cookie and is stored in an environment variable called HTTP_COOKIE_VARS. This variable is used while accessing cookies.
- Value − This sets the value of the named variable and is the content that you actually want to store.
- Expiry − This specify a future time in seconds since 00:00:00 GMT on 1st Aug 1947. After this time cookie will become inaccessible. If this parameter is not set then cookie will automatically expire when the Web Browser is closed.
- Path − This specifies the directories for which the cookie is valid. A single forward slash character permits the cookie to be valid for all directories.
- Domain − This can be used to specify the domain name in very large domains and must contain at least two periods to be valid. All cookies are only valid for the host and domain which created them.
- Security − This can be set to 1 to specify that the cookie should only be sent by secure transmission using HTTPS otherwise set to 0 which mean cookie can be sent by regular HTTP.
Cookies Variable($_COOKIE) with PHP.
$_COOKIE['variablenameofcookie'] is cookie variable which is used to retrieve user details.
PHP Cookie code example
<?php
setcookie("username", "monaj patel", time()+3600, "/","", 0);
setcookie("mobile", "99999999999", time()+3600, "/", "", 0);
?>
Put below code in another file.
<?
if(!isset($_COOKIE["username"])) {
echo "Sorry, cookie is not found!";
} else {
echo "
Cookie Value for username: " . $_COOKIE["username "];
}
?>
Output: Cookie Value for username: monaj patel
The setcookie()
function must appear BEFORE the tag
You can use isset() function to check if a cookie is set or not.
Deleting Cookie with PHP
You can set the cookie with a date that has already expired in setcookie() function as below.
<?php
setcookie("username", "monaj patel", time()-3600, "/","", 0);
setcookie("mobile", "99999999999", time()-3600, "/", "", 0);
?>
Comments