3

I am trying to create a REST API using Silex. It is working great, but now i want to use session variables to keep track of the user. I have tried to use regular php session variables, and SessionServiceProvider. For the life of me the session variables aren't persisting over page requests. Looking in my temp session folder, it appears that a new session is being created on every request.

So I have many php files included in the index.php file where the $app is initialized? I am not sure if that has anything to do with it, but it might make sense of what the follow code is doing.

index.php

<?php

require_once 'vendor/autoload.php';

$config['displayErrorDetails'] = true;

$app = new Silex\Application();
$app->register(new Silex\Provider\SessionServiceProvider, array('session.storage.save_path' => dirname(__DIR__) . '/tmp'));

$app->before(function() use ($app){
    $app['session']->start();
});

require "../apiSource/classes/employees.php";
$app->run();

employees.php

<?php
use Symfony\Component\HttpFoundation\JsonResponse as JsonResponse;
use Symfony\Component\HttpFoundation\Request as Request;

class Employees
{
    private $database;

    function __construct()
    {
        $this->database = getDB();
    }

    function loginEmployee($loginInfo, $app){

        //.... check loginInfo with database of employee ....///
        if ($isEmployee) {

            $app['session']->set('userID', $employee['e_ID']);
            return array('success' => 'success', 'e_ID' => $employee['e_ID'], 'session' => $app['session']->get('userID'));
            //SUCCESS
        } else {

            return array('message' => 'Error.');

        }

    }

    function isLoggedIn($app){
        $stmt = $this->database->prepare("SELECT e_ID, e_Email FROM Employee WHERE e_ID = ?");
        $stmt->execute(array($app['session']->get('userID')));
        $employee = $stmt->fetch(PDO::FETCH_ASSOC);

        if(empty($employee)){
            return array('Error' => $employee, 'Session' => $app['session']->get('userID'));
        }

        return $employee;
    }

    function logout($app){

        $app['session']->remove('userID');
        return array('success' => 'success');

    }
}


$app->get('/employees/logout', function() use ($app) {
    $employees = new Employees();
    $results = $employees->logout($app);

    return new JsonResponse($results);
});

$app->get('/employees/status', function() use ($app) {

    $employees = new Employees();
    $results = $employees->isLoggedIn($app);

    return new JsonResponse($results);

});

$app->post('/employees/login', function(Request $request) use ($app)  {

    $data = json_decode($request->getContent(), true);
    $request->request->replace(is_array($data) ? $data : array());

    $employee = new Employees();
    $results = $employee->loginEmployee($data, $app);

    return new JsonResponse($results);
});

When my Angular app posts a call to '{url}/employees/login' the session variable is set and it does return the session['userID']. However if right after that i call '{url}/employees/status' to see if the user is logged in, the session variable is empty. And in the tmp folder where the session variables are being saved i can see a new file created for every request.

What am I doing wrong? Any help would be appreciated.

Thanks!

EDIT

I have tried simplifying things here to see what is going on. It must be with my angular page posting and ill show what i mean.

index.php

$app->get('/hello', function () use ($app){
    session_start();
    $num = $_SESSION['idea'] ? $_SESSION['idea'] : 1;
    $_SESSION['idea'] =  $num+1;
    echoResponse(200, $_SESSION['idea']);
});

If I just visit that page and keep hitting refresh, my session variable is working and it is constantly going up by one. Thus session variable is working.

However when i try to call this page from my angular app:

$scope.hello = function(){
  $http.get('https://viromo.com/cubex/api/hello').then(function(results){
    console.log(results);
  })
};

Results keeps posting back the same number with out an increment. Not sure why this is happening. I have updated the title and tags to better reflect my questions target.

Thanks!

4
  • may be cookies are disabled.. Commented Mar 19, 2016 at 8:53
  • 1
    Did you check the PHPSESSID using dev. tools on your browser? Does the value change between pages? Commented Mar 19, 2016 at 10:37
  • 1
    have you tried to remove the $app['session']->start() from the middleware? according to this silex.sensiolabs.org/doc/providers/session.html seems no to be necessary. Commented Mar 19, 2016 at 11:30
  • Unfortunately cookies are enabled, PHPSESSID is getting a new var every time, and removeing the session start didnt help Commented Mar 25, 2016 at 21:28

1 Answer 1

1

In my case it was because a configuration was missing in angular to set the cookie in the request header.

Accordingly to this documentation: "By default, in cross-site XMLHttpRequest or Fetch invocations, browsers will not send credentials. A specific flag has to be set on the XMLHttpRequest object or the Request constructor when it is invoked."

In angular it is done by adding a config line:

angular.module('app', ['your_dependencies...'])
.config(function ($httpProvider) {
    // Enabling the use of cookies in angular
    $httpProvider.defaults.withCredentials = true;
});

If you're using Apache to host your backend, you may need to edit your '.htaccess', permitting the use of credentials by adding the following lines:

# When using credentials flag, the wildcard '*' does not work, so you need to specify the site URL
Header always set Access-Control-Allow-Origin http://<your_site_url>
# Allowing credentials
Header always set Access-Control-Allow-Credentials true
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.