Home >>Advance PHP Tutorial >PHP Set Cookie

PHP Set Cookie



PHP Set Cookie

A cookie is a text file saved to a user's system by a Web site. This file contains information that the site can retrieve on the user's next visit, thereby allowing the site to "recognize" the user and provide an enhanced set of features customized to that specific user.

Cookie have some important security features

  • A cookie can only be read by the Web site or domain that created it.
  • A single domain cannot set more than 20 cookies.
  • A single cookie cannot exceed 4 kilobytes in size.
  • The maximum number of cookies that may be set on a user's system is 300.

Set Cookie in PHP

The setcookie( ) function is used to set a cookie. Note : The setcookie( ) function must use BEFORE the <html> tag. Syntax

	setcookie(cookiename, value, expire, path, domain); 

In the given example, create a cookie named "cookie_user" and assign the value "abhi" to it. We also specify that the cookie should expire after one hour. Eg

<?php
	   
setcookie("cookie_name", "abhi", time()+60*60);
	   		
//OR
						
	     
$expire=time()+60*60;
             
etcookie("cookie_name", "abhi", $expire);				
	   
?>

Explain : In the example above cookie_name variale creates and assign value inside variable is "abhi" which work for 1 hour.


PHP get Cookie

The $_COOKIE[ ] super global variable is used to retrieve a cookie value. In the example below, we retrieve the value of the cookie named "cookie_name" and display it on a page:

<?php
	  
// Print a cookie
echo "Welcome ".$_COOKIE["cookie_name"];
   
?>
Output Welcome abhi

Note : It works for 1 hour after 1 hour cookie deleted automatically and if you try to access after destroyed cookie it gives an error message.

Set Multiple Cookie and get all Cookie

<?php
	  
//set cookie
setcookie("user", $_POST['n'] , time()+60*60);
	   
setcookie("age", $_POST['a'], time()+60*60);
	   
setcookie("profile", $_POST['prof'], time()+60*60);
   
?>
   
<html>
 
<body>
	
<form method="post">
	 
 Enter your name <input type="text" name="n"/><hr/>
	 
 Enter your age <input type="text" name="a"/><hr/>
	  
Enter your profile <input type="text" name="prof"/><hr/>
		
 <input type="submit" value="SET COOKIE"/&gt
	
</form>
 
</body>

</html>

Output :
Enter your name
Enter your age
Enter your profile

Retrieve all cookies

		
<?php 
	         	
print_r($_COOKIE);
		 
?>

Output Array ( [user] => abhi [age] => 25 [profile] => developer )

PHP delete Cookie

When deleting a cookie you should assure that the expiration date is in the past.

<?php
	  
// set the expiration date to one hour ago
setcookie("user", "abhi", time()-60*60);
   
?>