How to Create a Cookie in PHP?
Hi Friends,
Since I am new in PHP, can someone explain me what is Cookie in PHP. Also can anyone tell me how to create a cookie in PHP? Please give me detailed information as I don't know anything about the cookie. I know the cookies that we use during the Internet Explorer. Also if possible provide me the coding in PHP for creating and deleting cookie.!!:notworthy
Re: How to Create a Cookie in PHP?
I think that you know about the Cookie which gets created while using an Internet Explorer or any other browser. There is not much difference in between that Cookie and this one (its one and the same). A cookie is often used to identify a user. You can say that a cookie is a small file that the server embeds on the user's computer. When you requests a page with a browser, the computer will send the cookie along with the information. With PHP, you can both create and retrieve cookie values.
Re: How to Create a Cookie in PHP?
For setting a cookie you will have to use the setcookie() function. The setcookie() function must appear before the <html> tag. The Syntax for this function will be
Code:
setcookie(name, value, expire, path, domain);
For you to understand better, I have provided an example that will create a cookie having cookie named "admin" and assign the value "Counter-T". I have also specified that the cookie should expire after one hour. Here is code for that :
Code:
<?php
setcookie("admin", "Counter-T", time()+3600);
?>
<html>
.....
Re: How to Create a Cookie in PHP?
After looking at the example provided by the 'void'. I thought to provide an alternate coding for set the expiration time of the cookie in another way. It may be easier than using seconds. Because it will be difficult if you have to mention the 10 hours for expiry of cookie. Then you will have to calculate that first in seconds. So you can use this coding :
Code:
<?php
$expire=time()+60*60*24*30;
setcookie("admin", "Counter-T", $expire);
?>
<html>
.....
Re: How to Create a Cookie in PHP?
If you want to delete a cookie then you will have to make sure that the expiration date is in the past. Otherwise it will not delete. You can use the following code for deleting cookie :
Code:
<?php
// set the expiration date to one hour ago
setcookie("admin", "", time()-3600);
?>
I have considered the above example for deleting the cookie. So the name and value are the same.