File: src/Cookie.php

Recommend this page to a friend!
  Classes of Scott Arciszewski  >  Halite  >  src/Cookie.php  >  Download  
File: src/Cookie.php
Role: Class source
Content type: text/plain
Description: Class source
Class: Halite
Perform cryptography operations with libsodium
Author: By
Last change: For version 2, let's use strict types!
Merge branch 'v2.0' of https://github.com/paragonie/halite into v2.0

Conflicts:
src/Symmetric/Crypto.php
Date: 5 years ago
Size: 1,925 bytes
 

Contents

Class file image Download
<?php
declare(strict_types=1);
namespace
ParagonIE\Halite;

use \
ParagonIE\Halite\{
   
Alerts\InvalidMessage,
   
Symmetric\EncryptionKey,
   
Symmetric\Crypto
};

final class
Cookie
{
    protected
$key;
   
    public function
__construct(EncryptionKey $key)
    {
       
$this->key = $key;
    }
   
/**
     * Hide this from var_dump(), etc.
     *
     * @return array
     */
   
public function __debugInfo()
    {
        return [
           
'key' => 'private'
       
];
    }
   
   
/**
     * Store a value in an encrypted cookie
     *
     * @param string $name
     * @return mixed (typically an array)
     */
   
public function fetch(string $name)
    {
        if (!isset(
$_COOKIE[$name])) {
            return
null;
        }
        try {
           
$decrypted = Crypto::decrypt($_COOKIE[$name], $this->key);
            if (empty(
$decrypted)) {
                return
null;
            }
            return \
json_decode($decrypted, true);
        } catch (
InvalidMessage $e) {
            return
null;
        }
    }
   
   
/**
     * Store a value in an encrypted cookie
     *
     * @param string $name
     * @param mixed $value
     * @param int $expire (defaults to 0)
     * @param string $path (defaults to '/')
     * @param string $domain (defaults to NULL)
     * @param bool $secure (defaults to TRUE)
     * @param bool $httponly (defaults to TRUE)
     * @return bool
     */
   
public function store(
       
string $name,
       
$value,
       
int $expire = 0,
       
string $path = '/',
       
$domain = null,
       
bool $secure = true,
       
bool $httponly = true
   
): bool {
        return \
setcookie(
           
$name,
           
Crypto::encrypt(
                \
json_encode($value),
               
$this->key
           
),
           
$expire,
           
$path,
           
$domain,
           
$secure,
           
$httponly
       
);
    }
}


For more information send a message to info at phpclasses dot org.