We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Unable to get session in Library Class file

index.php Page :

<?php
use Phalcon\Mvc\Dispatcher as MvcDispatcher,
    Phalcon\Events\Manager as EventsManager,
    Phalcon\Session\Adapter\Files as SessionAdapter;
//error_reporting(E_ALL);
//error_reporting(E_ERROR | E_PARSE);
try {

    /**
     * Read the configuration from an external file
    */
    require __DIR__.'/../app/config/config.php';

    //set default timezone here
    date_default_timezone_set($config->timezone->default);

    $loader = new \Phalcon\Loader();

    /**
     * We're a registering a set of directories taken from the configuration file
     */
    $loader->registerDirs(
        array(
            __DIR__.$config->phalcon->controllersDir,
            __DIR__.$config->phalcon->libraryDir,
            __DIR__.$config->phalcon->modelsDir
        )
    )->register();

    /**
     * The FactoryDefault Dependency Injector automatically register the right services providing a full stack framework
     */
    $di = new \Phalcon\DI\FactoryDefault();

    /**
     * Load router from external file
     */
    $di->set('router', function(){
        require __DIR__.'/../app/config/routes.php';
        return $router;
    });

    /**
     * The URL component is used to generate all kind of urls in the application
     */
    $di->set('url', function() use ($config){
        $url = new \Phalcon\Mvc\Url();
        $url->setBaseUri($config->phalcon->baseUri);
        return $url;
    });

    /**
     * Setup the view service
     */
    $di->set('view', function() use ($config) {
        $view = new \Phalcon\Mvc\View();
        $view->setViewsDir(__DIR__.$config->phalcon->viewsDir);
        return $view;
    });

    //Set the views cache service
    $di->set('viewCache', function(){

        //Cache data for one day by default
        $frontCache = new Phalcon\Cache\Frontend\Output(array(
            "lifetime" => 2592000
        ));

        //File backend settings
        $cache = new Phalcon\Cache\Backend\File($frontCache, array(
            "cacheDir" => __DIR__."/../app/cache/",
            "prefix" => "php"
        ));

        return $cache;
    });

    /**
     * Database connection is created based in the parameters defined in the configuration file
     */
    $di->set('db', function() use ($config) {
        return new \Phalcon\Db\Adapter\Pdo\Mysql(array(
            "host" => $config->database->host,
            "username" => $config->database->username,
            "password" => $config->database->password,
            "dbname" => $config->database->dbname
        ));
    });

    /**
     * Start the session the first time some component request the session service
     */
    /* $di->set('session', function(){
        $session = new Phalcon\Session\Adapter\Files();
        $session->start();
        return $session;
    }); */
        /* $di->set("session",function(){
            $session = new Phalcon\Session\Adapter\Files();
            $session->start();
            return $session;
        }); */

    /**
     * Register the flash service with custom CSS classes
     */
    $di->set('flash', function(){
        $flash = new Phalcon\Flash\Direct(array(
            'error' => 'alert alert-danger',
            'success' => 'alert alert-success',
            'notice' => 'alert alert-info',
            'warning' => 'alert alert-warning',
        ));
        return $flash;
    });

    /* $di->setShared("session",function(){
        $session = new Session();
        $session->start();
        return $session;    
    }); */

        $di->setShared('session', function () {
            $session = new SessionAdapter();
            $session->start();

            return $session;
        });

    // Store config object
    $di->set('config', $config);

    $di->set('dispatcher', function () {

        // Create an EventsManager
        $eventsManager = new EventsManager();
        // Attach a listener
        $eventsManager->attach("dispatch:beforeDispatchLoop", function ($event, $dispatcher) {

                if(($dispatcher->getControllerName()=="user" && $dispatcher->getActionName()=="signup") || 
                    ($dispatcher->getControllerName()=="employee" && $dispatcher->getActionName()=="signupemployee") || 
                    ($dispatcher->getControllerName()=="user" && $dispatcher->getActionName()=="signin") ||
                    ($dispatcher->getControllerName()=="user" && $dispatcher->getActionName()=="checkemail") ||
                    ($dispatcher->getControllerName()=="user" && $dispatcher->getActionName()=="checkmobile") ||
                    ($dispatcher->getControllerName()=="misc" && $dispatcher->getActionName()=="saveotp") ||
                    ($dispatcher->getControllerName()=="misc" && $dispatcher->getActionName()=="sendmsg") ||
                    ($dispatcher->getControllerName()=="misc" && $dispatcher->getActionName()=="checkotp")||
                    ($dispatcher->getControllerName()=="service" && $dispatcher->getActionName()=="getservices")){
                    //Allow without accesstoken
                }else{

                $validAccessToken = new ValidAccessToken();
                if(!$validAccessToken->isValid()){
                    $dispatcher->setControllerName("sessionexpired");
                    $dispatcher->setActionName("error");
                }else{
                    $dispatcher->setParam("user_id", $validAccessToken->getUid());
                    $dispatcher->setParam("utype", $validAccessToken->getUtype());
                }
            }
        });

        $dispatcher = new MvcDispatcher();
        $dispatcher->setEventsManager($eventsManager);
        return $dispatcher;
    });

    $application = new \Phalcon\Mvc\Application();
    $application->setDI($di);
    echo $application->handle()->getContent();

} catch (Phalcon\Exception $e) {
    echo $e->getMessage();
} catch (PDOException $e){
    echo $e->getMessage();
}
?>

code to set session in Controller:

<?php
$accesstoken = '123456788fsdfsgsdgewfs';
$this->session->set("token", $accesstoken);
?>

Libary File to check set session is correct or not : But on this page not able to get session

<?php
session_start();
class ValidAccessToken{
    private $user_id;
    private $utype;

    function isValid(){
        $isvalid = false;
        if(isset($_POST['token'])){
            $tokenvalue  = $_POST['token'];
        }elseif(isset($_SESSION['token'])){
            $tokenvalue  = $_SESSION['token'];
        }else{
            $tokenvalue  = "";
        }
        echo 'TOKEN :  '.$tokenvalue."<br/>";
        if($tokenvalue){    
            $accessToken = AccessTokens::findFirstByToken($tokenvalue);
            if($accessToken){
                $this->user_id = $accessToken->user_id;
                $this->utype = $accessToken->utype;
                $isvalid = true;
            }
        }
        return $isvalid;
    }

    function getUid(){
        return $this->user_id;
    }

    function getUtype(){
        return $this->utype;
    }
}
?>
edited May '17

Don't use $_SESSION and $_POST, use $di->get("session")->get() and $di->get("request")->getPost()



85.5k

i am sorry if i am being annoying here, but i HATE if statments like this so much

 if(($dispatcher->getControllerName()=="user" && $dispatcher->getActionName()=="signup") || 
                    ($dispatcher->getControllerName()=="employee" && $dispatcher->getActionName()=="signupemployee") || 
                    ($dispatcher->getControllerName()=="user" && $dispatcher->getActionName()=="signin") ||
                    ($dispatcher->getControllerName()=="user" && $dispatcher->getActionName()=="checkemail") ||
                    ($dispatcher->getControllerName()=="user" && $dispatcher->getActionName()=="checkmobile") ||
                    ($dispatcher->getControllerName()=="misc" && $dispatcher->getActionName()=="saveotp") ||
                    ($dispatcher->getControllerName()=="misc" && $dispatcher->getActionName()=="sendmsg") ||
                    ($dispatcher->getControllerName()=="misc" && $dispatcher->getActionName()=="checkotp")||
                    ($dispatcher->getControllerName()=="service" && $dispatcher->getActionName()=="getservices"))
$allowedActions = ['user', 'signup'.....]

if (in_array($dispatcher->getControllerName(), $allowedActions) {
    ...
}

so much more readable ..

Also better just use acl xD