ZF2 Cookies for affiliates - php

I am attempting to write a cookie class to store referral information and need a bit of guidance.
The documentation on this seems a little sparse.
As with any affiliate programme, the idea is to grab information from a link: http://example.com/referrer_id=123 and to store this on the users computer for later use.
So this is what I have thus far:
Controller:
$cookieObject = new CookieService();
$cookieObject->setCookie(
[
'value' => [
'name' => 'test',
'referring_site'=>'test site'
]
]
);
die(var_dump($cookieObject->getCookie()));
CookieService class:
<?php
namespace Application\Library\Session;
use Zend\Http\Header\SetCookie;
use Zend\Http\Cookies;
class CookieService extends SetCookie
{
public function __construct() {
$this->cookie = new SetCookie();
$this->header = new Cookies();
}
/**
* Create a new cookie
* #param $params
*/
public function setCookie($params)
{
$key = (isset($params['key'])) ? $params['key'] : 'referrer';
$value = (isset($params['value'])) ? $params['value'] : [];
$expires = (isset($params['time'])) ? time() + $params['time'] : time() + 365 * 60 * 60 * 24;
/**
* Test whether the cookie exists before updating
*/
if (!$this->exists($key))
{
$this->cookie->setName($key);
$this->cookie->setValue($value);
$this->cookie->setExpires($expires);
$this->header->addCookie($this->cookie);
}
}
/**
* Get a cookie based on a given key
* #param string $key
* #return null
*/
public function getCookie($key = 'referrer')
{
$cookieArray = $this->header->getAllCookies();
foreach ($cookieArray AS $cookie)
{
if ($cookie->name === $key)
{
return $cookie;
}
}
return null;
}
/**
* Returns whether a cookie exists or not
* #param $key
* #return bool
*/
public function exists($key)
{
return ( $this->getCookie($key) ) ? true : false;
}
}
I am struggling with the following:
If I save a cookie then close the browser, the cookie is deleted. I can't seem to find any documentation that clearly covers this use.
Any advice, greatly appreciated.
ND: The dump of the cookie object:
object(Zend\Http\Header\SetCookie)[1085]
protected 'name' => string 'referrer' (length=8)
protected 'value' =>
array (size=2)
'name' => string 'test' (length=4)
'referring_site' => string 'test site' (length=9)
protected 'version' => null
protected 'maxAge' => null
protected 'expires' => int 1475931242
protected 'domain' => null
protected 'path' => null
protected 'secure' => boolean false
protected 'quoteFieldValue' => boolean false
protected 'httponly' => boolean false
public 'type' => string 'Cookie' (length=6)

Ok - so I have written my own class to deal with this. It is pretty simple:
<?php
namespace Application\Library\Session;
/**
* Use this service to set persistent cookies on a users machine
* Class CookieService
* #package Application\Library\Session
*/
class CookieService
{
/**
* Create a new cookie
* #param $params
*/
public function setCookie($params)
{
$name = (isset($params['name'])) ? $params['name'] : 'referrer';
$value = (isset($params['value'])) ? $params['value'] : '';
$expire = (isset($params['expire'])) ? time() + $params['expire'] : time() + 365 * 60 * 60 * 24;
$path = (isset($params['path'])) ? $params['path'] : '';
$domain = (isset($params['domain'])) ? $params['domain'] : '';
$secure = (isset($params['secure'])) ? $params['secure'] : 0;
$httponly = (isset($params['httponly'])) ? $params['httponly'] : 1;
/**
* Test whether the cookie exists before updating
*/
if (!$this->exists($name))
{
setcookie(
$name,
$value,
$expire ,
$path ,
$domain ,
$secure ,
$httponly
);
}
}
/**
* Get a cookie based on a given key
* #param string $name
* #return null
*/
public function getCookie($name = 'referrer')
{
return (isset($_COOKIE[$name])) ? $_COOKIE[$name] : null;
}
/**
* Returns whether a cookie exists or not
* #param $name
* #return bool
*/
public function exists($name)
{
return ( $this->getCookie($name) ) ? true : false;
}
/**
* Remove a cookie
* #param $name
*/
function deleteCookie($name)
{
if ($this->exists($name))
{
setcookie($name, "", time()-(60*60*24) );
}
}
}

Related

config\app.php getting values from database

I'm saving laravel app settings in database, but i can't use this trick in config\app.php. When i use in models or controllers withsetting('app.name') or \setting('app.url') working. But when i use this in config\app.php i'm getting this error;
Fatal error: Uncaught RuntimeException: A facade root has not been set. in /home/vagrant/SeraEnerji/vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php on line 234
( ! ) RuntimeException: A facade root has not been set. in /home/vagrant/SeraEnerji/vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php on line 234
Call Stack
# Time Memory Function Location
1 0.0001 401512 {main}( ) .../index.php:0
2 0.0252 821816 App\Http\Kernel->handle( ) .../index.php:55
3 0.0459 1270304 App\Http\Kernel->renderException( ) .../Kernel.php:120
4 0.0459 1270304 App\Exceptions\Handler->render( ) .../Kernel.php:326
5 0.0459 1270304 App\Exceptions\Handler->render( ) .../Handler.php:49
6 0.0463 1272856 App\Exceptions\Handler->prepareResponse( ) .../Handler.php:190
7 0.0467 1279088 App\Exceptions\Handler->renderHttpException( ) .../Handler.php:293
8 0.0467 1279088 App\Exceptions\Handler->registerErrorViewPaths( ) .../Handler.php:378
9 0.0514 1359464 Illuminate\Support\Facades\Facade::replaceNamespace( ) .../Handler.php:401
10 0.0514 1359840 Illuminate\Support\Facades\Facade::__callStatic( ) .../Handler.php:401
How can i get values from database for config\app.php?
İnfo: I'm followed this guide, https://www.qcode.in/save-laravel-app-settings-in-database/
My table:
id | name | val
----------------------------------------
1 | app_name | Site Name
2 | app_description | Site Description
3 | app_url | example.com
app\utils\helpers.php
<?php
if (! function_exists('setting')) {
function setting($key, $default = null)
{
if (is_null($key)) {
return new \App\Models\Setting\Setting();
}
if (is_array($key)) {
return \App\Models\Setting::set($key[0], $key[1]);
}
$value = \App\Models\Setting::get($key);
return is_null($value) ? value($default) : $value;
}
}
app\models\setting.php
<?php
namespace App\Models;
use Illuminate\Support\Collection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;
class Setting extends Model
{
/**
* The attributes that aren't mass assignable.
*
* #var array
*/
protected $guarded = [];
/**
* Add a settings value
*
* #param $key
* #param $val
* #param string $type
* #return bool
*/
public static function add($key, $val, $type = 'string')
{
if ( self::has($key) ) {
return self::set($key, $val, $type);
}
return self::create(['name' => $key, 'val' => $val, 'type' => $type]) ? $val : false;
}
/**
* Get a settings value
*
* #param $key
* #param null $default
* #return bool|int|mixed
*/
public static function get($key, $default = null)
{
if ( self::has($key) ) {
$setting = self::getAllSettings()->where('name', $key)->first();
return self::castValue($setting->val, $setting->type);
}
return self::getDefaultValue($key, $default);
}
/**
* Set a value for setting
*
* #param $key
* #param $val
* #param string $type
* #return bool
*/
public static function set($key, $val, $type = 'string')
{
if ( $setting = self::getAllSettings()->where('name', $key)->first() ) {
return $setting->update([
'name' => $key,
'val' => $val,
'type' => $type]) ? $val : false;
}
return self::add($key, $val, $type);
}
/**
* Remove a setting
*
* #param $key
* #return bool
*/
public static function remove($key)
{
if( self::has($key) ) {
return self::whereName($key)->delete();
}
return false;
}
/**
* Check if setting exists
*
* #param $key
* #return bool
*/
public static function has($key)
{
return (boolean) self::getAllSettings()->whereStrict('name', $key)->count();
}
/**
* Get the validation rules for setting fields
*
* #return array
*/
public static function getValidationRules()
{
return self::getDefinedSettingFields()->pluck('rules', 'name')
->reject(function ($val) {
return is_null($val);
})->toArray();
}
/**
* Get the data type of a setting
*
* #param $field
* #return mixed
*/
public static function getDataType($field)
{
$type = self::getDefinedSettingFields()
->pluck('data', 'name')
->get($field);
return is_null($type) ? 'string' : $type;
}
/**
* Get default value for a setting
*
* #param $field
* #return mixed
*/
public static function getDefaultValueForField($field)
{
return self::getDefinedSettingFields()
->pluck('value', 'name')
->get($field);
}
/**
* Get default value from config if no value passed
*
* #param $key
* #param $default
* #return mixed
*/
private static function getDefaultValue($key, $default)
{
return is_null($default) ? self::getDefaultValueForField($key) : $default;
}
/**
* Get all the settings fields from config
*
* #return Collection
*/
private static function getDefinedSettingFields()
{
return collect(config('setting_fields'))->pluck('inputs')->flatten(1);
}
/**
* caste value into respective type
*
* #param $val
* #param $castTo
* #return bool|int
*/
private static function castValue($val, $castTo)
{
switch ($castTo) {
case 'int':
case 'integer':
return intval($val);
break;
case 'bool':
case 'boolean':
return boolval($val);
break;
default:
return $val;
}
}
/**
* Get all the settings
*
* #return mixed
*/
public static function getAllSettings()
{
return Cache::rememberForever('settings.all', function() {
return self::all();
});
}
/**
* Flush the cache
*/
public static function flushCache()
{
Cache::forget('settings.all');
}
/**
* The "booting" method of the model.
*
* #return void
*/
protected static function boot()
{
parent::boot();
static::updated(function () {
self::flushCache();
});
static::created(function() {
self::flushCache();
});
}
}
Okay i found to solution. If there are people who have the same problem with me, the solution I found is as follows.
App\Providers\AppServiceProvider.php
<?php
namespace App\Providers;
use App\Models\Setting;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* #return void
*/
public function register()
{
//
}
/**
* Bootstrap any application services.
*
* #return void
*/
public function boot()
{
$settings = Setting::all()->pluck('val', 'name');
config()->set('settings', $settings);
Config::set([
'app.name' => \config('settings.app_name'),
'app.url' => \config('settings.app_url'),
]);
}
}

How can I use my session database with Zend's Session Manager?

When the Zend Session Manager from the tutorial starts a session, it generates a session key and posts a whole lot of data into the session. But I have a session system already set up with my own session keys and a different set of session data. How can I change the Zend configuration to use mine instead?
For reference, here is the Zend Session:
array (size=2)
'__ZF' =>
array (size=2)
'_REQUEST_ACCESS_TIME' => float 1468447555.1396
'_VALID' =>
array (size=3)
'Zend\Session\Validator\Id' => string 'xxxxxxxxxxxxxxxxxxxxxxxxxx' (length=26)
'Zend\Session\Validator\RemoteAddr' => string '--ip addr--' (length=13)
'Zend\Session\Validator\HttpUserAgent' => string '--user agent info--' (length=114)
'initialized' =>
object(Zend\Stdlib\ArrayObject)[371]
protected 'storage' =>
array (size=3)
'init' => int 1
'remoteAddr' => string '--ip addr--' (length=13)
'httpUserAgent' => string '--user agent info--' (length=114)
protected 'flag' => int 2
protected 'iteratorClass' => string 'ArrayIterator' (length=13)
protected 'protectedProperties' =>
array (size=4)
0 => string 'storage' (length=7)
1 => string 'flag' (length=4)
2 => string 'iteratorClass' (length=13)
3 => string 'protectedProperties' (length=19)
And here's what the session information I'm currently storing looks like (it's in a database, so I currently reference it with a Doctrine Entity):
object(MyModule\Entity\MySession)[550]
protected 'sessionid' => string 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' (length=40)
protected 'data1' => string 'xxxxx' (length=5)
protected 'data2' => string 'xxxxxxxxxxxx' (length=12)
protected 'datatime' =>
object(DateTime)[547]
public 'date' => string '2016-07-13 17:05:52.000000' (length=26)
public 'timezone_type' => int 3
public 'timezone' => string 'xxxxxxxxxxxxxxx' (length=15)
protected 'data3' => boolean false
protected 'data4' => string '' (length=0)
protected 'data5' => int 9
protected 'data6' => int 17765
protected 'data7' => boolean false
My code for the session manager comes from this SO answer, so I'm providing a link rather than repasting it and cluttering up this question.
The reason I want to use Zend Session Manager rather than simply referencing my stored session information with Doctrine is so that I have a layer between the my program and the stored session information - so then I can change the way I access the session information without having to change my entire program.
I ended up solving this on my own by extending the SessionManager, SessionStorage, and SessionSaveHandler classes and rewriting some of the functionality. I also changed the Module.php and module.config.php files. This is what the changes look like:
module.config.php
<?php
/* ...required use statements... */
return array(
'session' => array(
'config' => array(
'class' => 'Zend\Session\Config\SessionConfig',
'options' => array(
'name' => [my session name],
),
),
'storage' => 'MySession\Model\MySessionStorage',
'save_handler' => 'MySession\Model\MySessionSaveHandler'
),
'service_manager' => array(
'factories' => array(
'session_service' => function($serviceManager) {
$entityManager = $serviceManager->get('Doctrine\ORM\EntityManager');
return new SessionService($entityManager, 'MySession');
},
'MySession\Model\MySessionSaveHandler' => function($serviceManager) {
$sess = $serviceManager->get('onmysession_service');
/* #var $adapter \Zend\Db\Adapter\Adapter */
$adapter = $sm->get('Zend\Db\Adapter\Adapter');
$tableGateway = new TableGateway('mytablename', $adapter);
return new MySessionSaveHandler($tableGateway, new DbTableGatewayOptions(), $sess);
},
'MySessionManager' => function ($sm) {
$config = $sm->get('config');
if (isset($config['session'])) {
$session = $config['session'];
$sessionConfig = null;
if (isset($session['config'])) {
$class = isset($session['config']['class']) ? $session['config']['class'] : 'Zend\Session\Config\SessionConfig';
$options = isset($session['config']['options']) ? $session['config']['options'] : array();
$sessionConfig = new $class();
$sessionConfig->setOptions($options);
}
$sessionStorage = null;
if (isset($session['storage'])) {
$class = $session['storage'];
$sessionStorage = new $class();
}
$sessionSaveHandler = null;
if (isset($session['save_handler'])) {
// class should be fetched from service manager since it will require constructor arguments
$sessionSaveHandler = $sm->get($session['save_handler']);
}
$sessionManager = new MySessionManager($sessionConfig, $sessionStorage, $sessionSaveHandler);
} else {
$sessionManager = new MySessionManager();
}
MySession::setDefaultManager($sessionManager);
return $sessionManager;
},
),
),
'db' => array(
[db info here]
),
/***************************************************************************************************************
* Below is the doctrine configuration which holds information about the entities in this module and some
* other doctrine stuff like orm drivers etc.
***************************************************************************************************************/
'doctrine' => array(
'driver' => array(
'session_entities' => array(
'class' =>'Doctrine\ORM\Mapping\Driver\AnnotationDriver',
'cache' => 'array',
'paths' => array(__DIR__ . '/../src/MySession/Entity')
),
'orm_default' => array(
'drivers' => array(
'MySession\Entity' => 'session_entities'
),
),
),
),
);
Module.php
<?php
namespace MySession;
/* ...required use statements... */
/***************************************************************************************************
* This class holds a few utility functions related to loading the module and accessing config
* files for the module etc. These functions are primarily used by Zend under the hood.
***************************************************************************************************/
class Module implements AutoloaderProviderInterface, ConfigProviderInterface
{
public function onBootstrap(MvcEvent $e) {
$eventManager = $e->getApplication()->getEventManager();
// create the session manager
$moduleRouteListener = new ModuleRouteListener();
$moduleRouteListener->attach($eventManager);
$sessionManager = $e->getApplication()
->getServiceManager()
->get('MySessionManager');
$sessionManager ->start();
// attach dispatch listener to validate user session
$eventManager->attach(MvcEvent::EVENT_DISPATCH, array($sessionManager, 'handleSessionValidation')); // TODO: we already handleSessionValidation on bootstrap, find out if it's necessary to do it on dispatch as well
}
/***************************************************************************************************
* Returns the location of the module.config.php file. This function is used by the Zend Framework
* underneath the hood.
***************************************************************************************************/
public function getConfig()
{
return include __DIR__ . '/config/module.config.php';
}
/***************************************************************************************************
* Returns the Zend StandardAutoLoader which contains the directory structure of the module source
* folder.
***************************************************************************************************/
public function getAutoloaderConfig()
{
return array(
'Zend\Loader\StandardAutoloader' => array(
'namespaces' => array(
__NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
),
),
);
}
}
MySessionManager
<?php
namespace MySession\Model;
/* ...required use statements... */
class MySessionManager extends SessionManager
{
/**
* Is this session valid?
*
* A simple validation: checks if a row for the session name exists in the database
*
* #return bool
*/
public function isValid()
{
$id = $_COOKIE[SessionVariableNames::$SESSION_NAME];
return !is_null($this->getSaveHandler()->readMetadata($id));
}
/**
* checks if the session is valid and dies if not.
*/
public function handleSessionValidation() {
if(stristr($_SERVER["SCRIPT_NAME"],"login.php"))
{
// we don't need to check the session at the login page
return;
}
if (!$this->isValid()) {
die("Not logged in.")
}
}
/**
* Start session
*
* If no session currently exists, attempt to start it. Calls
* {#link isValid()} once session_start() is called, and raises an
* exception if validation fails.
*
* #param bool $preserveStorage If set to true, current session storage will not be overwritten by the
* contents of $_SESSION.
* #return void
* #throws RuntimeException
*/
public function start($preserveStorage = false)
{
if ($this->sessionExists()) {
return;
}
$saveHandler = $this->getSaveHandler();
if ($saveHandler instanceof SaveHandlerInterface) {
// register the session handler with ext/session
$this->registerSaveHandler($saveHandler);
}
// check if old session data exists and merge it with new data if so
$oldSessionData = [];
if (isset($_SESSION)) {
$oldSessionData = $_SESSION;
}
session_start();
if ($oldSessionData instanceof \Traversable
|| (! empty($oldSessionData) && is_array($oldSessionData))
) {
$_SESSION = ArrayUtils::merge($oldSessionData, $_SESSION, true); // this may not act like you'd expect, because the sessions are stored in ArrayObjects, so the second will always overwrite the first
}
$storage = $this->getStorage();
// Since session is starting, we need to potentially repopulate our
// session storage
if ($storage instanceof SessionStorage && $_SESSION !== $storage) {
if (!$preserveStorage) {
$storage->fromArray($_SESSION);
}
$_SESSION = $storage;
} elseif ($storage instanceof StorageInitializationInterface) {
$storage->init($_SESSION);
}
$this->handleSessionValidation();
}
/**
* Write session to save handler and close
*
* Once done, the Storage object will be marked as isImmutable.
*
* #return void
*/
public function writeClose()
{
// The assumption is that we're using PHP's ext/session.
// session_write_close() will actually overwrite $_SESSION with an
// empty array on completion -- which leads to a mismatch between what
// is in the storage object and $_SESSION. To get around this, we
// temporarily reset $_SESSION to an array, and then re-link it to
// the storage object.
//
// Additionally, while you _can_ write to $_SESSION following a
// session_write_close() operation, no changes made to it will be
// flushed to the session handler. As such, we now mark the storage
// object isImmutable.
$storage = $this->getStorage();
if (!$storage->isImmutable()) {
$_SESSION = $storage->toArray(true);
$this->saveHandler->writeMetadata(null, '_metadata');
$this->saveHandler->writeData($_SESSION['_data']);
session_write_close();
$storage->fromArray($_SESSION);
$storage->markImmutable();
}
}
}
MySessionStorage
<?php
namespace MySession\Model;
/* ...required use statements... */
class MySessionStorage extends SessionArrayStorage
{
/**
* Set storage metadata
*
* Metadata is used to store information about the data being stored in the
* object. Some example use cases include:
* - Setting expiry data
* - Maintaining access counts
* - localizing session storage
* - etc.
*
* #param string $key
* #param mixed $value
* #param bool $overwriteArray Whether to overwrite or merge array values; by default, merges
* #return ArrayStorage
* #throws Exception\RuntimeException
*/
public function setMetadata($key, $value, $overwriteArray = false)
{
if ($this->isImmutable()) {
throw new Exception\RuntimeException(
sprintf('Cannot set key "%s" as storage is marked isImmutable', $key)
);
}
// set the value
$sessVar = $_SESSION['_metadata'];
if (isset($sessVar[$key]) && is_array($value)) {
// data is array, check if we're replacing the whole array or modify/add to it
if ($overwriteArray) {
$sessVar[$key] = $value;
} else {
$sessVar[$key] = array_replace_recursive($sessVar[$key], $value);
}
} else {
// data is not an array, set or remove it in the session
if ((null === $value) && isset($sessVar[$key])) {
// remove data
$array = $sessVar;
unset($array[$key]);
$_SESSION[SessionVariableNames::$SESSION_METADATA] = $array; // we can't use $sessVar here because it's only a copy of $_SESSION
unset($array);
} elseif (null !== $value) {
// add data
$sessVar[$key] = $value;
}
}
return $this;
}
/**
* Retrieve metadata for the storage object or a specific metadata key
*
* Looks at session db for the metadata
*
* Returns false if no metadata stored, or no metadata exists for the given
* key.
*
* #param null|int|string $key
* #return mixed
*/
public function getMetadata($key = null)
{
if (!isset($_SESSION)) {
return false;
}
if (null === $key) {
return $_SESSION;
}
if (!array_key_exists($key, $_SESSION)) {
return false;
}
return $_SESSION[$key];
}
/**
* Set the request access time
*
* #param float $time
* #return ArrayStorage
*/
protected function setRequestAccessTime($time)
{
// make a metadata write call, since that sets a timestamp
$this->setMetadata('datatime', new DateTime("now"));
return $this;
}
}
MySessionSaveHandler
<?php
namespace MySession\Model;
/* ...required use statements... */
/**
* This class is the back end of the $_SESSION variable, when used together with a SessionStorage and SessionManager in a ZF module
*/
class MySessionSaveHandler implements SaveHandlerInterface
{
protected $sessionService;
private $tableGateway;
private $options;
private $sessionName;
private $sessionSavePath;
private $lifetime;
public function __construct(
TableGateway $tableGateway,
DbTableGatewayOptions $options,
ISessionService $sessionService)
{
$this->tableGateway = $tableGateway;
$this->options = $options;
$this->sessionService = $sessionService;
}
protected function getSessionService()
{
return $this->sessionService;
}
/**
* Read session data
*
* #param string $id
* #return string
*/
public function read($id)
{
// Get data from database
$metadata = $this->readMetadata($id);
// Put data in PHP-session-serialized form
$data = "_metadata|".serialize($metadata);
return $data;
}
/**
* Read session metadata
*
* #param string $id
* #return mixed
*/
public function readMetadata($id = null)
{
if (is_null($id))
{
if (!array_key_exists('sessionid', $_COOKIE))
{
// can't get id from cookie
return null;
}
$id = $_COOKIE['sessionid'];
}
if ($data = $this->getSessionService()->findById($id))
{
return $data->getArrayCopy();
}
return null;
}
/** deprecated, use writeMetadata instead
* Write session data
*
* #param string $id
* #param string $data
* #return bool
* Note sessions use an alternative serialization method.
*/
public function write($id, $data)
{
// don't use this because $data is serialized strangely and can't be automatically inserted into my table
}
/**
* Write session metadata
*
* #param string $id
* #param array $data an associative array matching a row in the table
* #return mixed
*/
public function writeMetadata($id = null, $data = null)
{
if (is_null($id))
{
if (!array_key_exists('sessionid', $_COOKIE))
{
// can't get id from cookie
return null;
}
$id = $_COOKIE['sessionid'];
}
// get the session info from the database so we can modify it
$sessionService = $this->getSessionService();
$session = $sessionService->findByID($id);
if (is_null($session)) {
$session = new \MyModule\Entity\MySession();
}
if (!is_null($data))
{
// overwrite the stored data
$session->setDataFromArray($data);
}
return $sessionService->save($session);
}
/**
* Destroy session - deletes data from session table
*
* #param string $id The session ID being destroyed.
* #return bool
* The return value (usually TRUE on success, FALSE on failure).
* Note this value is returned internally to PHP for processing.
*/
public function destroy($id)
{
$this->getSessionService()->delete($id);
return true;
}
/**
* Garbage Collection - cleanup old sessions
*
* #param int $maxlifetime
* Sessions that have not updated for
* the last maxlifetime seconds will be removed.
* #return bool
* The return value (usually TRUE on success, FALSE on failure).
* Note this value is returned internally to PHP for processing.
*/
public function gc($maxlifetime)
{
$metadata = $this->readMetadata(); // gets session id from cookie, then gets session from that
if (!is_null($metadata))
{
$datatime = $metadata['datatime'];
$previousTime = (new DateTime($datatime))->getTimestamp();
// if (current time - datatime) > maxlifetime, destroy the session
$val = time() - $previousTime;
if ($val > $maxlifetime) {
$this->destroy($metadata['sessionid']);
}
}
}
}
The end result of all this is that you can access information stored in the database simply by accessing the $_SESSION variable, because the data gets loaded from the database into the $_SESSION variable on bootstrap, and the $_SESSION variable is written back into the database when the session is closed (which as I understand it, happens when the page is sent to the client).

updating User using webvimark in yii2

I am using webvimark module in Yii2. I have created a My Account page, where a user can update his/her information. I am unable to update user updated info, although I am able to fetch user info and display in a form on my-account page.
Below is my updated webvimark User class:
/**
* This is the model class for table "user".
*
* #property string $name
* #property string $country
* #property string $card_number
* #property string $payment_type
* #property string $expiring_month
* #property string $expiring_year
* #property string $expiry_date
* #property string $csc
* #property string $card_address
* #property string $city
* #property string $state
* #property string $zip_code
* #property string $user_type
* #property string $fax
* #property string $address
* #property string $phone
* #property string $user_type
* #property string $company_name
* #property integer $id
* #property string $username
* #property string $email
* #property integer $email_confirmed
* #property string $auth_key
* #property string $password_hash
* #property string $confirmation_token
* #property string $bind_to_ip
* #property string $registration_ip
* #property integer $status
* #property integer $superadmin
* #property integer $created_at
* #property integer $updated_at
*/
class User extends UserIdentity
{
const STATUS_ACTIVE = 1;
const STATUS_INACTIVE = 0;
const STATUS_BANNED = -1;
/**
* #var string
*/
public $gridRoleSearch;
/**
* #var string
*/
public $password;
/**
* #var string
*/
public $repeat_password;
/**
* Store result in singleton to prevent multiple db requests with multiple calls
*
* #param bool $fromSingleton
*
* #return static
*/
public static function getCurrentUser($fromSingleton = true)
{
if ( !$fromSingleton )
{
return static::findOne(Yii::$app->user->id);
}
$user = Singleton::getData('__currentUser');
if ( !$user )
{
$user = static::findOne(Yii::$app->user->id);
Singleton::setData('__currentUser', $user);
}
return $user;
}
/**
* Assign role to user
*
* #param int $userId
* #param string $roleName
*
* #return bool
*/
public static function assignRole($userId, $roleName)
{
try
{
Yii::$app->db->createCommand()
->insert(Yii::$app->getModule('user-management')->auth_assignment_table, [
'user_id' => $userId,
'item_name' => $roleName,
'created_at' => time(),
])->execute();
AuthHelper::invalidatePermissions();
return true;
}
catch (\Exception $e)
{
return false;
}
}
/**
* Revoke role from user
*
* #param int $userId
* #param string $roleName
*
* #return bool
*/
public static function revokeRole($userId, $roleName)
{
$result = Yii::$app->db->createCommand()
->delete(Yii::$app->getModule('user-management')->auth_assignment_table, ['user_id' => $userId, 'item_name' => $roleName])
->execute() > 0;
if ( $result )
{
AuthHelper::invalidatePermissions();
}
return $result;
}
/**
* #param string|array $roles
* #param bool $superAdminAllowed
*
* #return bool
*/
public static function hasRole($roles, $superAdminAllowed = true)
{
if ( $superAdminAllowed AND Yii::$app->user->isSuperadmin )
{
return true;
}
$roles = (array)$roles;
AuthHelper::ensurePermissionsUpToDate();
return array_intersect($roles, Yii::$app->session->get(AuthHelper::SESSION_PREFIX_ROLES,[])) !== [];
}
/**
* #param string $permission
* #param bool $superAdminAllowed
*
* #return bool
*/
public static function hasPermission($permission, $superAdminAllowed = true)
{
if ( $superAdminAllowed AND Yii::$app->user->isSuperadmin )
{
return true;
}
AuthHelper::ensurePermissionsUpToDate();
return in_array($permission, Yii::$app->session->get(AuthHelper::SESSION_PREFIX_PERMISSIONS,[]));
}
/**
* Useful for Menu widget
*
* <example>
* ...
* [ 'label'=>'Some label', 'url'=>['/site/index'], 'visible'=>User::canRoute(['/site/index']) ]
* ...
* </example>
*
* #param string|array $route
* #param bool $superAdminAllowed
*
* #return bool
*/
public static function canRoute($route, $superAdminAllowed = true)
{
if ( $superAdminAllowed AND Yii::$app->user->isSuperadmin )
{
return true;
}
$baseRoute = AuthHelper::unifyRoute($route);
if ( Route::isFreeAccess($baseRoute) )
{
return true;
}
AuthHelper::ensurePermissionsUpToDate();
return Route::isRouteAllowed($baseRoute, Yii::$app->session->get(AuthHelper::SESSION_PREFIX_ROUTES,[]));
}
/**
* getStatusList
* #return array
*/
public static function getStatusList()
{
return array(
self::STATUS_ACTIVE => UserManagementModule::t('back', 'Active'),
self::STATUS_INACTIVE => UserManagementModule::t('back', 'Inactive'),
self::STATUS_BANNED => UserManagementModule::t('back', 'Banned'),
);
}
/**
* getStatusValue
*
* #param string $val
*
* #return string
*/
public static function getStatusValue($val)
{
$ar = self::getStatusList();
return isset( $ar[$val] ) ? $ar[$val] : $val;
}
/**
* #inheritdoc
*/
public static function tableName()
{
return Yii::$app->getModule('user-management')->user_table;
}
/**
* #inheritdoc
*/
public function behaviors()
{
return [
TimestampBehavior::className(),
];
}
/**
* #inheritdoc
*/
public function rules()
{
return [
['username', 'required'],
[['name','phone','user_type'], 'required'],
['username', 'unique'],
['username', 'trim'],
[['company_name', 'name', 'phone','fax','address','payment_type','card_number','expiry_date','csc','card_address','country','city','state','zip_code'], 'trim'],
[['status', 'email_confirmed'], 'integer'],
['email', 'email'],
['email', 'validateEmailConfirmedUnique'],
['bind_to_ip', 'validateBindToIp'],
['bind_to_ip', 'trim'],
['bind_to_ip', 'string', 'max' => 255],
['password', 'required', 'on'=>['newUser', 'changePassword']],
['password', 'string', 'max' => 255, 'on'=>['newUser', 'changePassword']],
['password', 'trim', 'on'=>['newUser', 'changePassword']],
['repeat_password', 'required', 'on'=>['newUser', 'changePassword']],
['repeat_password', 'compare', 'compareAttribute'=>'password'],
];
}
/**
* Check that there is no such confirmed E-mail in the system
*/
public function validateEmailConfirmedUnique()
{
if ( $this->email )
{
$exists = User::findOne([
'email' => $this->email,
'email_confirmed' => 1,
]);
if ( $exists AND $exists->id != $this->id )
{
$this->addError('email', UserManagementModule::t('front', 'This E-mail already exists'));
}
}
}
/**
* Validate bind_to_ip attr to be in correct format
*/
public function validateBindToIp()
{
if ( $this->bind_to_ip )
{
$ips = explode(',', $this->bind_to_ip);
foreach ($ips as $ip)
{
if ( !filter_var(trim($ip), FILTER_VALIDATE_IP) )
{
$this->addError('bind_to_ip', UserManagementModule::t('back', "Wrong format. Enter valid IPs separated by comma"));
}
}
}
}
/**
* #return array
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'username' => UserManagementModule::t('back', 'Login'),
'superadmin' => UserManagementModule::t('back', 'Superadmin'),
'confirmation_token' => 'Confirmation Token',
'registration_ip' => UserManagementModule::t('back', 'Registration IP'),
'bind_to_ip' => UserManagementModule::t('back', 'Bind to IP'),
'status' => UserManagementModule::t('back', 'Status'),
'gridRoleSearch' => UserManagementModule::t('back', 'Roles'),
'created_at' => UserManagementModule::t('back', 'Created'),
'updated_at' => UserManagementModule::t('back', 'Updated'),
'password' => UserManagementModule::t('back', 'Password'),
'repeat_password' => UserManagementModule::t('back', 'Repeat password'),
'email_confirmed' => UserManagementModule::t('back', 'E-mail confirmed'),
'email' => 'E-mail',
//'user_type' => 'E-mail',
];
}
/**
* #return \yii\db\ActiveQuery
*/
public function getRoles()
{
return $this->hasMany(Role::className(), ['name' => 'item_name'])
->viaTable(Yii::$app->getModule('user-management')->auth_assignment_table, ['user_id'=>'id']);
}
/**
* Make sure user will not deactivate himself and superadmin could not demote himself
* Also don't let non-superadmin edit superadmin
*
* #inheritdoc
*/
public function beforeSave($insert)
{
if ( $insert )
{
if ( php_sapi_name() != 'cli' )
{
$this->registration_ip = LittleBigHelper::getRealIp();
}
$this->generateAuthKey();
}
else
{
// Console doesn't have Yii::$app->user, so we skip it for console
if ( php_sapi_name() != 'cli' )
{
if ( Yii::$app->user->id == $this->id )
{
// Make sure user will not deactivate himself
$this->status = static::STATUS_ACTIVE;
// Superadmin could not demote himself
if ( Yii::$app->user->isSuperadmin AND $this->superadmin != 1 )
{
$this->superadmin = 1;
}
}
// Don't let non-superadmin edit superadmin
if ( isset($this->oldAttributes['superadmin']) && !Yii::$app->user->isSuperadmin && $this->oldAttributes['superadmin'] == 1 )
{
return false;
}
}
}
// If password has been set, than create password hash
if ( $this->password )
{
$this->setPassword($this->password);
}
return parent::beforeSave($insert);
}
/**
* Don't let delete yourself and don't let non-superadmin delete superadmin
*
* #inheritdoc
*/
public function beforeDelete()
{
// Console doesn't have Yii::$app->user, so we skip it for console
if ( php_sapi_name() != 'cli' )
{
// Don't let delete yourself
if ( Yii::$app->user->id == $this->id )
{
return false;
}
// Don't let non-superadmin delete superadmin
if ( !Yii::$app->user->isSuperadmin AND $this->superadmin == 1 )
{
return false;
}
}
return parent::beforeDelete();
}
}
and the AuthController class because I have created my view file (my-account.php inside auth folder of webvimark). My AuthController action function is as under:
public function actionMyAccount()
{
$model = new User();
if ( Yii::$app->user->isGuest )
{
return $this->goHome();
}
//if ( Yii::$app->request->post() AND $model->validate())
if ( Yii::$app->request->post())
{
if($model->load(Yii::$app->request->post()) )
{
$model->save();
Yii::$app->session->setFlash('message', "Account has been updated!");
}
}
else
{
$model = User::getCurrentUser();
}
return $this->render('my-account', ['model' => $model,]);
}
Could be you must declare the field you don't validate by the safe attribute
[['company_name', 'name', 'phone','fax','address','payment_type',
'card_number','expiry_date','csc','card_address','country',
'city','state','zip_code'], 'safe'],
or could be is a validation problem
try using (just for debug) save(false)
//if ( Yii::$app->request->post() AND $model->validate())
if ( Yii::$app->request->post())
{
if($model->load(Yii::$app->request->post()) )
{
$model->save(false);
Yii::$app->session->setFlash('message', "Account has been updated!");
} else {
var_dump('model not loaded');
}
}
if in this way the values are saved in db the is a validation rule problem .
You can get the validation error this way
if ($model->validate()) {
// all inputs are valid
} else {
// validation failed: $errors is an array containing error messages
$errors = $model->errors;
var_dump($errors);
}

Why I am getting Class "SoapClient' not found in..etc" [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
WAMP Stack PHP “Fatal error: Class ‘SoapClient’ not found”
I downloaded a library from this site library and when I tried to use it's examples it says : "Fatal error: Class 'SoapClient' not found in C:\wamp\www\Amazon-ECS\Exeu-Amazon-ECS-PHP-Library-9030053\lib\AmazonECS.class.php on line 231" How should I able to fix this?
<?php
/**
* Amazon ECS Class
* http://www.amazon.com
* =====================
*
* This class fetchs productinformation via the Product Advertising API by Amazon (formerly ECS).
* It supports three basic operations: ItemSearch, ItemLookup and BrowseNodeLookup.
* These operations could be expanded with extra prarmeters to specialize the query.
*
* Requirement is the PHP extension SOAP.
*
* #package AmazonECS
* #license http://www.gnu.org/licenses/gpl.txt GPL
* #version 1.3.4-DEV
* #author Exeu <exeu65#googlemail.com>
* #contributor Julien Chaumond <chaumond#gmail.com>
* #link http://github.com/Exeu/Amazon-ECS-PHP-Library/wiki Wiki
* #link http://github.com/Exeu/Amazon-ECS-PHP-Library Source
*/
class AmazonECS
{
const RETURN_TYPE_ARRAY = 1;
const RETURN_TYPE_OBJECT = 2;
/**
* Baseconfigurationstorage
*
* #var array
*/
private $requestConfig = array(
'requestDelay' => false
);
/**
* Responseconfigurationstorage
*
* #var array
*/
private $responseConfig = array(
'returnType' => self::RETURN_TYPE_OBJECT,
'responseGroup' => 'Small',
'optionalParameters' => array()
);
/**
* All possible locations
*
* #var array
*/
private $possibleLocations = array('de', 'com', 'co.uk', 'ca', 'fr', 'co.jp', 'it', 'cn', 'es');
/**
* The WSDL File
*
* #var string
*/
protected $webserviceWsdl = 'http://webservices.amazon.com/AWSECommerceService/AWSECommerceService.wsdl';
/**
* The SOAP Endpoint
*
* #var string
*/
protected $webserviceEndpoint = 'https://webservices.amazon.%%COUNTRY%%/onca/soap?Service=AWSECommerceService';
/**
* #param string $accessKey
* #param string $secretKey
* #param string $country
* #param string $associateTag
*/
public function __construct($accessKey, $secretKey, $country, $associateTag)
{
if (empty($accessKey) || empty($secretKey))
{
throw new Exception('No Access Key or Secret Key has been set');
}
$this->requestConfig['accessKey'] = $accessKey;
$this->requestConfig['secretKey'] = $secretKey;
$this->associateTag($associateTag);
$this->country($country);
}
/**
* execute search
*
* #param string $pattern
*
* #return array|object return type depends on setting
*
* #see returnType()
*/
public function search($pattern, $nodeId = null)
{
if (false === isset($this->requestConfig['category']))
{
throw new Exception('No Category given: Please set it up before');
}
$browseNode = array();
if (null !== $nodeId && true === $this->validateNodeId($nodeId))
{
$browseNode = array('BrowseNode' => $nodeId);
}
$params = $this->buildRequestParams('ItemSearch', array_merge(
array(
'Keywords' => $pattern,
'SearchIndex' => $this->requestConfig['category']
),
$browseNode
));
return $this->returnData(
$this->performSoapRequest("ItemSearch", $params)
);
}
/**
* execute ItemLookup request
*
* #param string $asin
*
* #return array|object return type depends on setting
*
* #see returnType()
*/
public function lookup($asin)
{
$params = $this->buildRequestParams('ItemLookup', array(
'ItemId' => $asin,
));
return $this->returnData(
$this->performSoapRequest("ItemLookup", $params)
);
}
/**
* Implementation of BrowseNodeLookup
* This allows to fetch information about nodes (children anchestors, etc.)
*
* #param integer $nodeId
*/
public function browseNodeLookup($nodeId)
{
$this->validateNodeId($nodeId);
$params = $this->buildRequestParams('BrowseNodeLookup', array(
'BrowseNodeId' => $nodeId
));
return $this->returnData(
$this->performSoapRequest("BrowseNodeLookup", $params)
);
}
/**
* Implementation of SimilarityLookup
* This allows to fetch information about product related to the parameter product
*
* #param string $asin
*/
public function similarityLookup($asin)
{
$params = $this->buildRequestParams('SimilarityLookup', array(
'ItemId' => $asin
));
return $this->returnData(
$this->performSoapRequest("SimilarityLookup", $params)
);
}
/**
* Builds the request parameters
*
* #param string $function
* #param array $params
*
* #return array
*/
protected function buildRequestParams($function, array $params)
{
$associateTag = array();
if(false === empty($this->requestConfig['associateTag']))
{
$associateTag = array('AssociateTag' => $this->requestConfig['associateTag']);
}
return array_merge(
$associateTag,
array(
'AWSAccessKeyId' => $this->requestConfig['accessKey'],
'Request' => array_merge(
array('Operation' => $function),
$params,
$this->responseConfig['optionalParameters'],
array('ResponseGroup' => $this->prepareResponseGroup())
)));
}
/**
* Prepares the responsegroups and returns them as array
*
* #return array|prepared responsegroups
*/
protected function prepareResponseGroup()
{
if (false === strstr($this->responseConfig['responseGroup'], ','))
return $this->responseConfig['responseGroup'];
return explode(',', $this->responseConfig['responseGroup']);
}
/**
* #param string $function Name of the function which should be called
* #param array $params Requestparameters 'ParameterName' => 'ParameterValue'
*
* #return array The response as an array with stdClass objects
*/
protected function performSoapRequest($function, $params)
{
if (true === $this->requestConfig['requestDelay']) {
sleep(1);
}
$soapClient = new SoapClient(
$this->webserviceWsdl,
array('exceptions' => 1)
);
$soapClient->__setLocation(str_replace(
'%%COUNTRY%%',
$this->responseConfig['country'],
$this->webserviceEndpoint
));
$soapClient->__setSoapHeaders($this->buildSoapHeader($function));
return $soapClient->__soapCall($function, array($params));
}
/**
* Provides some necessary soap headers
*
* #param string $function
*
* #return array Each element is a concrete SoapHeader object
*/
protected function buildSoapHeader($function)
{
$timeStamp = $this->getTimestamp();
$signature = $this->buildSignature($function . $timeStamp);
return array(
new SoapHeader(
'http://security.amazonaws.com/doc/2007-01-01/',
'AWSAccessKeyId',
$this->requestConfig['accessKey']
),
new SoapHeader(
'http://security.amazonaws.com/doc/2007-01-01/',
'Timestamp',
$timeStamp
),
new SoapHeader(
'http://security.amazonaws.com/doc/2007-01-01/',
'Signature',
$signature
)
);
}
/**
* provides current gm date
*
* primary needed for the signature
*
* #return string
*/
final protected function getTimestamp()
{
return gmdate("Y-m-d\TH:i:s\Z");
}
/**
* provides the signature
*
* #return string
*/
final protected function buildSignature($request)
{
return base64_encode(hash_hmac("sha256", $request, $this->requestConfig['secretKey'], true));
}
/**
* Basic validation of the nodeId
*
* #param integer $nodeId
*
* #return boolean
*/
final protected function validateNodeId($nodeId)
{
if (false === is_numeric($nodeId) || $nodeId <= 0)
{
throw new InvalidArgumentException(sprintf('Node has to be a positive Integer.'));
}
return true;
}
/**
* Returns the response either as Array or Array/Object
*
* #param object $object
*
* #return mixed
*/
protected function returnData($object)
{
switch ($this->responseConfig['returnType'])
{
case self::RETURN_TYPE_OBJECT:
return $object;
break;
case self::RETURN_TYPE_ARRAY:
return $this->objectToArray($object);
break;
default:
throw new InvalidArgumentException(sprintf(
"Unknwon return type %s", $this->responseConfig['returnType']
));
break;
}
}
/**
* Transforms the responseobject to an array
*
* #param object $object
*
* #return array An arrayrepresentation of the given object
*/
protected function objectToArray($object)
{
$out = array();
foreach ($object as $key => $value)
{
switch (true)
{
case is_object($value):
$out[$key] = $this->objectToArray($value);
break;
case is_array($value):
$out[$key] = $this->objectToArray($value);
break;
default:
$out[$key] = $value;
break;
}
}
return $out;
}
/**
* set or get optional parameters
*
* if the argument params is null it will reutrn the current parameters,
* otherwise it will set the params and return itself.
*
* #param array $params the optional parameters
*
* #return array|AmazonECS depends on params argument
*/
public function optionalParameters($params = null)
{
if (null === $params)
{
return $this->responseConfig['optionalParameters'];
}
if (false === is_array($params))
{
throw new InvalidArgumentException(sprintf(
"%s is no valid parameter: Use an array with Key => Value Pairs", $params
));
}
$this->responseConfig['optionalParameters'] = $params;
return $this;
}
/**
* Set or get the country
*
* if the country argument is null it will return the current
* country, otherwise it will set the country and return itself.
*
* #param string|null $country
*
* #return string|AmazonECS depends on country argument
*/
public function country($country = null)
{
if (null === $country)
{
return $this->responseConfig['country'];
}
if (false === in_array(strtolower($country), $this->possibleLocations))
{
throw new InvalidArgumentException(sprintf(
"Invalid Country-Code: %s! Possible Country-Codes: %s",
$country,
implode(', ', $this->possibleLocations)
));
}
$this->responseConfig['country'] = strtolower($country);
return $this;
}
/**
* Setting/Getting the amazon category
*
* #param string $category
*
* #return string|AmazonECS depends on category argument
*/
public function category($category = null)
{
if (null === $category)
{
return isset($this->requestConfig['category']) ? $this->requestConfig['category'] : null;
}
$this->requestConfig['category'] = $category;
return $this;
}
/**
* Setting/Getting the responsegroup
*
* #param string $responseGroup Comma separated groups
*
* #return string|AmazonECS depends on responseGroup argument
*/
public function responseGroup($responseGroup = null)
{
if (null === $responseGroup)
{
return $this->responseConfig['responseGroup'];
}
$this->responseConfig['responseGroup'] = $responseGroup;
return $this;
}
/**
* Setting/Getting the returntype
* It can be an object or an array
*
* #param integer $type Use the constants RETURN_TYPE_ARRAY or RETURN_TYPE_OBJECT
*
* #return integer|AmazonECS depends on type argument
*/
public function returnType($type = null)
{
if (null === $type)
{
return $this->responseConfig['returnType'];
}
$this->responseConfig['returnType'] = $type;
return $this;
}
/**
* Setter/Getter of the AssociateTag.
* This could be used for late bindings of this attribute
*
* #param string $associateTag
*
* #return string|AmazonECS depends on associateTag argument
*/
public function associateTag($associateTag = null)
{
if (null === $associateTag)
{
return $this->requestConfig['associateTag'];
}
$this->requestConfig['associateTag'] = $associateTag;
return $this;
}
/**
* #deprecated use returnType() instead
*/
public function setReturnType($type)
{
return $this->returnType($type);
}
/**
* Setting the resultpage to a specified value.
* Allows to browse resultsets which have more than one page.
*
* #param integer $page
*
* #return AmazonECS
*/
public function page($page)
{
if (false === is_numeric($page) || $page <= 0)
{
throw new InvalidArgumentException(sprintf(
'%s is an invalid page value. It has to be numeric and positive',
$page
));
}
$this->responseConfig['optionalParameters'] = array_merge(
$this->responseConfig['optionalParameters'],
array("ItemPage" => $page)
);
return $this;
}
/**
* Enables or disables the request delay.
* If it is enabled (true) every request is delayed one second to get rid of the api request limit.
*
* Reasons for this you can read on this site:
* https://affiliate-program.amazon.com/gp/advertising/api/detail/faq.html
*
* By default the requestdelay is disabled
*
* #param boolean $enable true = enabled, false = disabled
*
* #return boolean|AmazonECS depends on enable argument
*/
public function requestDelay($enable = null)
{
if (false === is_null($enable) && true === is_bool($enable))
{
$this->requestConfig['requestDelay'] = $enable;
return $this;
}
return $this->requestConfig['requestDelay'];
}
}
The error appears to be caused by the version of PHP that you have does not have the SOAP extension enabled.
To resolve this simply start wamp, click on the wamp system tray icon. Within this screen select PHP then PHP extensions. This will display a list of extensions. Ensure that php_soap is ticked.
If you intend to access soap servers that use HTTPs then you will also ensure php_openssl is ticked.

How to use my Cookie class properly

I just started with OOP programming in PHP and I have made a cookie class.
With doing that i have got a few questions unanswered
is my class correct?
how do I use it properly in my page? ( lets think i want to see how many times the visitor visited my website before and output the result for the user )
I already tested it after loging in and using this code:
$cookie = new Cookie();
$cookie->store();
print_r($_COOKIE);
(I had a result thrown back but I don't know if its the good result)
Bellow you can find my Cookie class.
<?php
class Cookie {
/* cookie $id */
private $id = false;
/* cookie life $time */
private $time = false;
/* cookie $domain */
private $domain = false;
/* cookie $path */
private $path = false;
/* cookie $secure (true is https only) */
private $secure = false;
public function __construct ($id, $time = 3600, $path = false, $domain = false, $secure = false) {
$this->id = $id;
$this->time = $time;
$this->path = $path;
$this->domain = $domain;
$this->secure = $secure;
}
public function store() {
foreach ($this->parameters as $parameter => $validator) {
setcookie($this->id . "[" . $parameter . "]", $validator->getValue(), time() + $this->time, $this->path, $this->domain, $this->secure, true);
}
}
public function restore() {
if (isset($_COOKIE[$this->id])) {
foreach ($_COOKIE[$this->id] as $parameter => $value) {
$this->{$parameter} = $value;
}
}
}
public function destroy() {
$this->time = -1;
}
}
?>
I hope someone can give me a good example! thanks for the help in advance!
This code should do the most frequent tasks you'll need to manipulate cookies.
Don't get confused by reading the getter and setter methods - they're used to access the private variables defined in the class.
Have in mind this class is used per cookie and you need to have a new instance for every new cookie you'll operate over.
Below the class I've added an example how to use the class.
<?php
/**
* Cookie manager.
*/
class Cookie
{
/**
* Cookie name - the name of the cookie.
* #var bool
*/
private $name = false;
/**
* Cookie value
* #var string
*/
private $value = "";
/**
* Cookie life time
* #var DateTime
*/
private $time;
/**
* Cookie domain
* #var bool
*/
private $domain = false;
/**
* Cookie path
* #var bool
*/
private $path = false;
/**
* Cookie secure
* #var bool
*/
private $secure = false;
/**
* Constructor
*/
public function __construct() { }
/**
* Create or Update cookie.
*/
public function create() {
return setcookie($this->name, $this->getValue(), $this->getTime(), $this->getPath(), $this->getDomain(), $this->getSecure(), true);
}
/**
* Return a cookie
* #return mixed
*/
public function get(){
return $_COOKIE[$this->getName()];
}
/**
* Delete cookie.
* #return bool
*/
public function delete(){
return setcookie($this->name, '', time() - 3600, $this->getPath(), $this->getDomain(), $this->getSecure(), true);
}
/**
* #param $domain
*/
public function setDomain($domain) {
$this->domain = $domain;
}
/**
* #return bool
*/
public function getDomain() {
return $this->domain;
}
/**
* #param $id
*/
public function setName($id) {
$this->name = $id;
}
/**
* #return bool
*/
public function getName() {
return $this->name;
}
/**
* #param $path
*/
public function setPath($path) {
$this->path = $path;
}
/**
* #return bool
*/
public function getPath() {
return $this->path;
}
/**
* #param $secure
*/
public function setSecure($secure) {
$this->secure = $secure;
}
/**
* #return bool
*/
public function getSecure() {
return $this->secure;
}
/**
* #param $time
*/
public function setTime($time) {
// Create a date
$date = new DateTime();
// Modify it (+1hours; +1days; +20years; -2days etc)
$date->modify($time);
// Store the date in UNIX timestamp.
$this->time = $date->getTimestamp();
}
/**
* #return bool|int
*/
public function getTime() {
return $this->time;
}
/**
* #param string $value
*/
public function setValue($value) {
$this->value = $value;
}
/**
* #return string
*/
public function getValue() {
return $this->value;
}
}
/**
* Create a cookie with the name "myCookieName" and value "testing cookie value"
*/
$cookie = new Cookie();
// Set cookie name
$cookie->setName('myCookieName');
// Set cookie value
$cookie->setValue("testing cookie value");
// Set cookie expiration time
$cookie->setTime("+1 hour");
// Create the cookie
$cookie->create();
// Get the cookie value.
print_r($cookie->get());
// Delete the cookie.
//$cookie->delete();
?>
P.S. I've commented the $cookie->delete(); on purpose so that you can see the content of print_r($cookie->get()).
Edit:
Question: Where does the code go to see if the cookie is set?
Answer:
You should check what does $_COOKIE do in the php documentation.
Basically the server sends headers to the client's browser which stores the cookies on the client's computer. When the client initializes a connection to the server it passes the cookies with the request.
Question: Where goes the $cookie->delete();
Answer:
There isn't a direct way to delete cookies. So in order to do that you need to create a cookie with the same name and expiration time which is in the past. When you do that the cookie is removed from the client's browser.

Categories