Show DevBest [PHP] OOP Cookie Wrapper

Markshall

Русский Стандарт
Contributor
Dec 18, 2010
2,637
2,389
A lot of people have trouble with cookies in PHP, they're rather tricky to manipulate and can be a pain, this I've coded this cookie wrapper class today to make it easier for myself when I'm coding projects and thought I'd be generous and share it.

I've tested it and it works fine without any problems as far as I am aware, if you come across a problem, let me know and I'll see to it if I'm not busy.

It is a static class so you do not need to instantiate it, you can just include the file and use it whenever you like.

The code is commented and I will show a few usage demonstrations after the code to show you how to use it.

[/URL]
PHP:
<?php
/**
* @desc Cookie wrapper coded in OOP PHP that reduces the hassle of PHP cookies.
* @author Mark Eriksson
* @webpage http://mark-eriksson.com
*/

date_default_timezone_set('Europe/London');
class Cookie {
    const Session = 0;
    const ADay    = 86400;
    const AWeek  = 604800;
    const AMonth  = 2592000; //technically this is only 30 days.
    const AYear  = 31536000;

    static public function Day($amount=1) {
        if (!is_numeric($amount) || !is_int($amount) || $amount>200) $amount=1;
       
        return (self::ADay*$amount);
    }
   
    static public function Week($amount=1) {
        if (!is_numeric($amount) || !is_int($amount) || $amount>200) $amount=1;
       
        return (self::AWeek*$amount);
    }
   
    static public function Month($amount=1) {
        if (!is_numeric($amount) || !is_int($amount) || $amount>200) $amount=1;
       
        return (self::AMonth*$amount);
    }
    static public function Year($amount=1) {
        if (!is_numeric($amount) || !is_int($amount) || $amount>200) $amount=1;
       
        return (self::AYear*$amount);
    }
   
    static public function Exists($cookie) {
        return (isset($_COOKIE[$cookie]));
    }
   
    static public function IsEmpty($cookie) {
        return (empty($_COOKIE[$cookie]));
    }
   
    static public function Get($cookie, $def_value='') {
        return ((self::Exists($cookie)) ? $_COOKIE[$cookie] : $def_value);
    }
   
    static public function Set($cookie, $value, $options=array()) {
        $default_options = array('expiry'  => self::Year(),
                                'path'    => '/',
                                'domain'  => (bool)true,
                                'secure'  => (bool)false,
                                'httponly' => (bool)false
                                );
        $cookie_set = false;
       
        if (!headers_sent()) {
            foreach ($default_options as $option_key=>$option_value) {
                if (!array_key_exists($option_key, $options)) $options[$option_key] = $default_options[$option_value];
            }
           
            $options['domain'] = (($options['domain'] === true) ? ('.' . $_SERVER['HTTP_HOST']) : '');
           
            $options['expiry'] = (int)((is_numeric($options['expiry']) ? ($options['expiry']+=time()) : strtotime($options['expiry']));
           
            $cookie_set = @setcookie($cookie, $value, $options['expiry'], $options['path'], $options['domain'], $options['secure'], $options['httponly']);
            if ($cookie_set) $_COOKIE[$cookie] = $value;
        }
       
        return $cookie_set;
    }
   
    static public function Remove($cookie, $options=array()) {
        $default_options = array('path'        => '/',
                                'domain'      => (bool)true,
                                'secure'      => (bool)false,
                                'httponly'    => (bool)false,
                                'globalremove' => (bool)true
                                );
        $return = false;
       
        if (!headers_sent()) {
            foreach ($default_options as $option_key=>$option_value) {
                if (!array_key_exists($option_key, $options)) $options[$option_key] = $default_options[$option_value];
            }
           
            $options['domain'] = (($options['domain'] === true) ? ('.' . $_SERVER['HTTP_HOST']) : '');
           
            if ($options['globalremove']) unset($_COOKIE[$cookie]);
           
            $return = @setcookie($cookie, '', (time()-3600), $options['path'], $options['domain'], $options['secure'], $options['httponly']);
        }
       
        return $return;
    }
}
?>

Usage demonstrations

Sets a cookie called 'rememberme' with value 'yes' that will expire after 2 months.
PHP:
<?php
include('class.cookie.php');
Cookie::Set('rememberme', 'yes', array('expiry' => Cookie::Month(2)));
?>

Checks if a cookie exists.
PHP:
<?php
include('class.cookie.php');
Cookie::Set('rememberme', 'yes');
var_dump(Cookie::Exists('rememberme')); //true
var_dump(Cookie::Exists('trolol')); //false
?>

Checks if a cookie is empty (means the cookie exists, but has an empty value).
PHP:
<?php
include('class.cookie.php');
Cookie::Set('test', 'valuehere');
var_dump(Cookie::IsEmpty('rememberme')); //false

Cookie::Set('test', '');
var_dump(Cookie::IsEmpty('test')); //true
?>

Gets the value of a cookie called 'rememberme'.
PHP:
<?php
include('class.cookie.php');
var_dump(Cookie::Get('rememberme')); //'yes'
?>

Removes a cookie called 'rememberme'.
PHP:
<?php
include('class.cookie.php');
var_dump(Cookie::Remove('rememberme')); //true
?>

I hope it helps you with any future projects if you decide to use it.
- Mark.
 
Last edited:

Sysode

Front-End Developer
Dec 11, 2012
1,673
848
Sorry if I sound nooby here but what's actually better, cookies or sessions?

Depending on who I ask, I get a different answer each time. Mind explaining the benefits of having cookies > sessions?

Anyways, on topic, another nice release and the commenting makes it easier to understand.
 

Markshall

Русский Стандарт
Contributor
Dec 18, 2010
2,637
2,389
Sorry if I sound nooby here but what's actually better, cookies or sessions?

Depending on who I ask, I get a different answer each time. Mind explaining the benefits of having cookies > sessions?

Anyways, on topic, another nice release and the commenting makes it easier to understand.
It depends really on what you want to do. Although cookies can be edited, they are useful to web developers.

And cheers.
 

Users who are viewing this thread

Top