AngularJS ngRoute and PHP $_SESSION variables
Asked Answered
E

4

8

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?

Exhibitionism answered 28/2, 2014 at 2:34 Comment(9)
I really don't understand anything :( Why do you have 3 php files?Kreit
AngularJS routing is single page linking, meaning that there is no server interaction besides ajax calls. You would need to make an ajax call to request $_SESSION variablesReahard
I would assume ngRoute does make ajax calls because anything else that I echo in display.php works just fine. So it must be a server interaction.Exhibitionism
Don't understand what you trying to do. can't visualize any of these $routeProvider/server routing/rewrite base on your descriptionUnroot
Basically in any AngularJS single page application I can't get PHP $_SESSION variables to work as they seem to require you to load the page via a refresh to get the updated variables values. Running the pages using $http in AngularJS seems to do something differently then running the page in the browser. phpFiddle is down at the moment. I will adds a phpFiddle when the website is back up.Exhibitionism
The problem might be that ajax calls do not set cookies and your session isn't set because you have no session_id to identify it? Try at first handling that. You could make an ajax call that does the login/auth stuff and starts the session and also returns a session id. then you have to add that session id to every call (i.e. as a parameter in the url) and check it in all your php to open the correct session.Crabbe
_If you want i could try to write an answer explaining that in more detail but i am still not sure if that is what you are asking aboutCrabbe
I am starting the session with session_start() in index.php and running that again in display.php before trying to echo a $_SESSION variable. The actually session variable IS updated however is seems that AngularJS (the ajax call) can't see it's new value and displays the old value. However if I refresh the page (causing a page load and not an ajax call) the updated variable is shown correctly. So I am sure it is using the correct session I seem to be able to set the $_SESSION variables via AngularJS(ajax) but not get them. I can only get the initial values that were set at initial page load.Exhibitionism
If you sure that ajax call is occurs, then i advice you add this to url in your request: 'path/to/display.php?'+Date.now();. May be you can't see session because the browser cache.Subcontraoctave
C
8

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
Crabbe answered 12/3, 2014 at 14:25 Comment(2)
Thank you, Yes it seems that the templates can't access sessions variables (yet they still execute php?). I now run $http.get to get and set my sessions variables and then assign them to $scope to use in my application. I didn't have to worry about the session id stuff it was always using the same session. Thanks for pointing me in the right direction. Still not 100% sure why templates execute php files differently than an ajax call.Exhibitionism
@Exhibitionism Templates execute different because they are rendered in your first call. The user isn't logged in, the session was just created (if at all) and thus there is not information. After calling the login.php via ajax, your templates do not get rendered in php again because you do not reload the page. You get it now?Crabbe
B
1

In general, no reason exists, why AngularJS apps, which request PHP-based server-side stuff, won't be able to read $_SESSION.

That said, please provide at least the core concepts of of your AngularJS code, so we can provide further details.

Additionally, put just this in display.php:

<?

echo __FILE__
   . '<br />' . date( DATE_RFC822 )
   . '<br />' . var_dump( $_SESSION )
   ;

// intentionally skipped dangerous closing PHP-tag

Now run your AngularJS app and tell what comes out.

Brewhouse answered 6/3, 2014 at 22:27 Comment(0)
R
1

Make sure you start the session before reading the SESSION variables.

<?php
    session_start();
    echo $_SESSION["user9"];
?>
Raptorial answered 10/3, 2014 at 23:56 Comment(0)
M
0

I don't think you're looking for angularJS. I think you're looking for something more like this.

index.php:

<html>
    <header>
       <title>Login</title>
    </header>
    <body>
       <form method="POST" action="login.php">
           <input type="username" name="username" placeholder="username" />
           <input type="password" name="password" placeholder="password" />
           <input type="submit" value="Login" />
       </form>
    </body>
</html>

login.php

<?php
   session_start();
   if(empty($_POST)) {
      die("You don't have permission to be here.");
   } elseif(empty($_POST['username']) or empty($_POST['password'])) {
      die("All fields are required.");
   }

   $username = "admin";
   $password = "password";

   if($_POST['password'] == $password && $_POST['username'] == $username) {
       $_SESSION['loggedIn'] == "true";
       header("Location: show.php");
   } else {
       die("Invalid login");
   }
?>

show.php

 <?php
    if($_SESSION['loggedIn'] == "true") {
        echo "You are logged in";
    } else {
        die("You don't have permission to be here.");
    }
 ?>
Moir answered 10/3, 2014 at 12:59 Comment(1)
Yes of course that works, I am trying to get this working when using AngularJS. AngularJS allows you to have a single page application.Exhibitionism

© 2022 - 2024 — McMap. All rights reserved.