Ir para conteúdo

Arquivado

Este tópico foi arquivado e está fechado para novas respostas.

Nerdmonkey

Classe para gerenciar sessões

Recommended Posts

Boa noite a todos.

Avaliando a classe abaixo saberiam dizer o porque dessa mensagem de erro:

 

Fatal error: Cannot use object of type stdClass as array in D:\Server\public_html\Session.class.php on line 92

 

 

A linha 92 contém esse trecho de código:

 

'siteviews_users' => $this->traffic['siteviews_users'] + 1,

 

 

 

<?php

/**
* Class Session
* This class is responsible for all sessions, users online and traffic
* She's responsible for yourself, just call the object for it and let she work
*
* @author Samuel dos Santos
*/
class Session extends Read
{
/** @var datetime */
private $date;

/** @var int */
private $cache;

/** @var mixed */
private $traffic;

/** @var string */
private $browser;

/** @var mixed */
private $cookie;

/** @var mixed */
private $create;

/** @var mixed */
private $update;

public function __construct($cache = null)
{
// Enable to create new sessions
session_start();
// Check the session status
$this->checkSession($cache);
}

/**
* @param null $cache
*/
private function checkSession($cache = null)
{
// Actual date
$this->date = date('Y-m-d');
// Value for navigator cache
$this->cache = ((int) $cache ? $cache : 20);
// Manage sessions actions
$this->checkObjectSession();
// Cleanup this @var from memory system
$this->date = null;
}

/**
* Manager the object session for user navigate
*/
private function checkObjectSession()
{
if(empty($_SESSION['useronline'])):
// When session not exist, we create it and insert in database
$this->setTraffic();
// Initialize sessions
$this->setSession();
else:
// Some for debug
$this->setTraffic();

// Update sessions
$this->sessionUpdate();
endif;
}

/**
* Check and inset the traffic in table ws_siteviews
*/
private function setTraffic()
{
$this->getTraffic();
$this->create = new Create;
$this->update = new Update;

if(!$this->traffic):
// If initialize, we have a first visit of a day
$this->create->ExeCreate('ws_siteviews', ['siteviews_date' => $this->date, 'siteviews_users' => 1, 'siteviews_views' => 1, 'siteviews_pages' => 1]);
else:
if(!$this->getCookie()):
$this->update->ExeUpdate(
'ws_siteviews',
[
'siteviews_users' => $this->traffic['siteviews_users'] + 1,
'siteviews_views' => $this->traffic['siteviews_views'] + 1,
'siteviews_pages' => $this->traffic['siteviews_pages'] + 1
],
'WHERE siteviews_date = :date',
"date={$this->date}"
);
else:
$this->update->ExeUpdate('ws_siteviews', ['siteviews_views' => $this->traffic['siteviews_views'] + 1, 'siteviews_pages' => $this->traffic['siteviews_pages'] + 1], 'WHERE siteviews_date = :date', "date={$this->date}");
endif;
endif;
}

/**
* Set all attributes for our session
*/
private function setSession()
{
$_SESSION['useronline'] = [
'online_session' => session_id(),
'online_startviews' => date('Y-m-d H:is:s'),
'online_endview' => date('Y-m-d H:is:s', strtotime("+{$this->cache}minutes")),
'online_ip' => filter_input(INPUT_SERVER, 'REMOTE_ADDR', FILTER_VALIDATE_IP),
'online_url' => filter_input(INPUT_SERVER, 'REQUEST_URI', FILTER_DEFAULT),
'online_agent' => filter_input(INPUT_SERVER, 'HTTP_USER_AGENT', FILTER_DEFAULT)
];
}

/**
* Update user session
*/
private function sessionUpdate()
{
$_SESSION['useronline']['online_endview'] = date('Y-m-d H:is:s', strtotime("+{$this->cache}minutes"));
$_SESSION['useronline']['online_url'] = filter_input(INPUT_SERVER, 'REQUEST_URI', FILTER_DEFAULT);
}

/**
* Read table ws_siteviews for obtain a traffic for current day
* @return boolean
*/
private function getTraffic()
{
// Read the table ws_siteviews searching for rows with today's date
parent::ExeRead('ws_siteviews', 'WHERE siteviews_date = :date', "date={$this->date}");
// The next method, is check if this query have any results and store it in @var mixed $traffic
$this->thisResultTraffic();
}

/**
* Check if query got any result for interaction with it
* @return boolean
*/
private function thisResultTraffic()
{
if(parent::getRowCount()):
// Store a unique row value
$this->traffic = parent::getResult()[0];
endif;
}

/**
* Obtain a cookie value
*/
private function getCookie()
{
// Store cookie value for actual user
$this->cookie = filter_input(INPUT_COOKIE, 'useronline', FILTER_DEFAULT);
// Next method, will check if this cookie is empty or not
$this->thisResultCookie();
// Create a new cookie for user navigate
setcookie('useronline', base64_encode('samueldossantos'), time() + 86400);
}

/**
* Check the cookie value
* @return boolean
*/
private function thisResultCookie()
{
if($this->cookie):
// When exist
return true;
else:
// When not exst
return false;
endif;
}
}

Compartilhar este post


Link para o post
Compartilhar em outros sites

  • Conteúdo Similar

    • Por Negrito
      Olá,
       
      Estou quebrando a cabeça com o recurso Session_OnStart , pois eu gostaria que algumas paginas/arquivos .asp tivessem exceções.
       
      Criei o Global.ASA com o seguinte contexto:
       
      <SCRIPT RUNAT=Server Language="VBScript">
      Sub Session_OnStart
        startPage = "/default.asp"
        currentPage = Request.ServerVariables("SCRIPT_NAME")
        If strcomp(currentPage,startPage,1) then
          Response.Redirect("/default.asp")
        End If
      End Sub
      </SCRIPT>
       
      Ele funciona perfeitamente, quando tento acessar qualquer pagina ou subdiretorio diretamente pela URL, ele me joga para a pagina inicial.
       
      Porem, eu gostaria de ter exceções em alguns diretorios e paginas .ASP , onde eu gostaria de liberar o acesso direto ao digitar a URL.
       
      Alguem sabe me informar se é possivel ? 
       
      Obrigado.
       
       
    • Por k9studio
      Olá meus Amigos,
       
      Estou tendo dificuldades em eliminar dados repetidos de uma session
      é um sisteminha de pesquisa de domínios com array
      quero eliminar quando já tiver um nome na session, não deixar gravar outro
      aguem pode ajudar
      veja como está  
      Array ( [0] => Array ( [type] => register [domain] => testeteste.com.br [regperiod] => 1 ) [1] => Array ( [type] => register [domain] => testeteste.com [regperiod] => 1 ) [2] => Array ( [type] => register [domain] => testeteste.net.br [regperiod] => 1 ) [3] => Array ( [type] => register [domain] => testeteste.com.br [regperiod] => 1 ) [4] => Array ( [type] => register [domain] => testeteste.com [regperiod] => 1 ) [5] => Array ( [type] => register [domain] => testeteste.net.br [regperiod] => 1 ) ) Desde já muito obrigado a todos
    • Por Alberto Nascimento
      Estou tendo problemas de acesso ao Session, onde quando realizo login via computador, consigo "pegar" os dados que foram armazenados na sesion, mas quando utilizo o sistema de login no telefone ( android, por exemplo ) a session não esta conseguindo carregar os dados do usuário logado e exibir na página seguinte.
       
      Outra coisa que observei é que não consigo trabalhar com session em pastas diferentes, isso é normal? Veja só:
       
       
      Utilizando esta estrutura, não consigo ter acesso ao session no sistema ANDROID
       
      Agora se ao invés de ser como esta acima, faço uma pasta com todos os arquivos juntos, já consigo "pegar" os dados da session. Isso é normal?
    • Por tony_lu
      Ola pessoal, tenho uma hospedagem de php na hostgator e estou tentando rodar uma rotina com session e esta dando erro, na pagina só tem este código:
       
      <?php  session_start();  ?> E esta dando este erro:
      Warning: session_start(): Cannot send session cache limiter - headers already sent (output started at /home2/sitewww/public_html/carrinho.php:1) in /home2/sitewww/public_html/carrinho.php on line 2
       
      Alguem pode me ajudar?
    • Por Evandrorussi
      Olá pessoal,
       
      Trabalho com PHP a uns 6 anos e me deparei com um problema de session que nunca ouvi falar, pelo menos não encontrei nada pela internet desse tipo. Tenho um servidor dedicado no Google Cloud e o site tem um sistema de login via session. O problema é que a session funciona aleatoriamente, tem hora que não funciona, o cliente troca de tela e o servidor perde a session e pede pra logar novamente, isso não acontece com todos usuários, comigo por exemplo não acontece.
      O cara que trabalha comigo não ocorria esse problema mas agora começou a acontecer e ele reparou que com guia anônima o problema não ocorre.
       
      Caso alguém pergunte, session_start() está iniciando em todas as páginas.
       
      Abraço
       
       
×

Informação importante

Ao usar o fórum, você concorda com nossos Termos e condições.