|
Development -
Javascript
|
|
Written by Rick
|
|
Friday, 20 March 2009 00:00 |
|
Web development, sooner or later, requires dealing with cookies. I've found using Javascript to handle cookies preferable over using php. Reason; "Header already sent" errors. Generally reading a cookie is not a problem in php and requires less code.
Here's some code I've gathered and modified for my own use for cookie manipulation;
Â
function set_cookie( name, value, expires ) { //expects //( 'name', 'value', '#days' )
// set time, it's in milliseconds var today = new Date(); today.setTime( today.getTime() );
/* if the expires variable is set, make the correct expires time, the current script below will set it for x number of days, to make it for hours, delete * 24, for minutes, delete * 60 * 24 */ if ( expires ) { expires = expires * 1000 * 60 * 60 * 24; } var expires_date = new Date( today.getTime() + (expires) );
document.cookie = name + "=" +escape( value ) + ( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ); }
Â
function get_cookie ( cookie_name ) { var results = document.cookie.match ( '(^|;) ?' + cookie_name + '=([^;]*)(;|$)' );
if ( results ) return ( unescape ( results[2] ) ); else return null; }
Â
function delete_cookie ( cookie_name ) { var cookie_date = new Date ( );Â // current date & time cookie_date.setTime ( cookie_date.getTime() - 1 ); document.cookie = cookie_name += "=; expires=" + cookie_date.toGMTString(); }
Â
|