If you want to store data on your website visitors computers then you'll need to use cookies. They are a very useful way of improving the user friendliness of your sites by, for example, keeping your users logged in over multiple sessions on the same PC, or recording which language, text size or colour options they prefer to view your site in.
Cookies can be accessed in several ways by all sorts of different coding languages, but as we do alot of work with PHP and javascript we will show how we access and manipulate cookies with those languages.
PHP:
There is an inbuilt function in PHP called setcookie() which can be used for all your cookie related fun in PHP. Its full details can be found here: http://php.net/manual/en/function.setcookie.php but we have given you the basics below:
setcookie("cookie name", "cookie value", "expiry time (secs)", "path", "domain");
In essence all you need to do to store a cookie of 'language'='eng' for 1 month which is valid across your entire domain is to put the following code somewhere on your php page:
setcookie("language", "eng", time()+(3600*24*30), "/");
It should go above any html output as there can be header issues, but apart from that it really is that simple! To retrieve your cookie value in PHP use the $_COOKIE array.
Javascript:
We have created some javascript functions to simplify the process of cookie manipulation in javascript. These are provided below for your use.
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i <>
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
function eraseCookie(name) {
createCookie(name,"",-1);
}
Sunday, 6 June 2010
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment