AngularJS ngRoute and PHP $_SESSION variables

Craig picture Craig · Feb 28, 2014 · Viewed 17.1k times · Source

I have 3 pages:

  1. index.php
  2. login.php
  3. display.php

index.php

Sets up AngularJS using the ngRoute module to navigate my pages.

login.php

Loaded by default and sets PHP $_SESSION variables.

display.php

Echos the contents of $_SESSION.

I navigate to display.php from login.php using a link setup with ngRoute.

Problem

display.php does not show $_SESSION variables no matter how many times I navigate to and from it. It will only display them if I manually navigate to the page such as refreshing the page or entering the address in the browser.

I know the php code is executed because I can echo other things to the screen it just doesn't access the $_SESSION variables.

Why is this?

Answer

Andresch Serj picture Andresch Serj · Mar 12, 2014

I think i might see where your problem is. You try to access php session in your single page angularJS HTML templates am i right? like:

<div ng-repeat="n in <?php $_SESSION['someSessionArray'] ?>">

That is not how it works. Your $_SESSION will never be available in your templates. What you can do, is use an ajax request for your login authentication and have that request give you a session id. Then use that session id when starting your session in further ajax requests (as already mentioned).

Then, when you want to store something to the php session, access the data via ajax request and php service.

a VERY, VERY, VERY, simple Example: inside getFromSession.php

session_start($_GET['session_id']);
$key = $_GET['key']
echo json_encode($_SESSION[$key]);

inside storeToSession.php

session_start($_GET['session_id']);
$key = $_GET['key'];
$value = $_GET['value'];
$_SESSION[$key] = $value;

inside your login.php

$user = yourAuthMechanism($_GET['username'],$_GET['password']);
if($user) {
  session_start();
  echo json_decode(array('status' => 'success','sid' => session_id()));
}
else { ... error handling

inside anywhere in your angular where you need to access session data:

$promise = $http.get('pathtoyourphp/getFromSession.php?key=foo');
$http.set('pathtoyourphp/getFromSession.php?key=bar&value=4');
// now use promise to acces the data you got from your service