0

I have a user session with some variables:

if(!isset($_SESSION)) {
    session_name('User Session'); 
    session_start(); 
}

$private_id = session_id(); 
$private_counter;
$private_max;
$private_startTime;

session_write_close(); 

and now i call an init function to initialize these variables:

function init($counter, $max, $startTime) {
    global $private_counter;
    global $private_max;
    global $private_startTime;

    $private_counter = $counter;
    $private_max = $max;
    $private_startTime = $startTime;

    $data = array(
        "counter" => $private_counter, 
        "max" => $private_max,
        "startTime" => $private_startTime
    );

    echo json_encode($data);
}

This returns for example the following:

counter: 12
max: 20
startTime: 1437309883114

So i thought the variables are set now but in another method which i call later i do the following:

function diff($endTime) {
    global $private_startTime;

    $diffTime = $endTime - $private_startTime;

    $data = array(
        "time" => $diffTime
    );

    echo json_encode($data);
 }

And now the $diffTime is always the $endTime because $private_startTime is null. But why is it null? I initialized the variable with 1437309883114 using the function init($counter, $max, $startTime). Is something happen when i use the global statement?

How else could i access my user variables inside functions if im not allowed to use global?

EDIT

The complete PHP-File:

<?PHP

error_reporting(E_ALL);
ini_set('display_errors', 1);

date_default_timezone_set("Europe/Berlin");

if(isset($_POST["action"]) && !empty($_POST["action"])) {
    $action = $_POST["action"];
    $startTime;
    $endTime;

    if(isset($_POST["startTime"]) && !empty($_POST["startTime"])) {
        $startTime = $_POST["startTime"];
    }

    if(isset($_POST["endTime"]) && !empty($_POST["endTime"])) {
        $endTime = $_POST["endTime"];
    }

    switch($action) {
        case "init" : init($startTime); break;
        case "check" : check($endTime); break;
    }
}

if(!isset($_SESSION)) {
    session_name('User Session'); 
    session_start(); 
}

$private_id = session_id(); 
$private_counter;
$private_max;
$private_startTime;

session_write_close(); 

/**
 *
 *
 */
function init($startTime) {
    global $private_counter;
    global $private_max;
    global $private_startTime;

    $private_counter = 1;
    $private_max = 15;
    $private_startTime = $startTime;

    $data = array(
        "counter" => $private_counter, 
        "max" => $private_max,
        "startTime" => $private_startTime,
    );

    echo json_encode($data);
}

/**
 *
 *
 */
function check($endTime) {
    global $private_startTime;

    $diffTime = $endTime - $private_startTime;

    $data = array(
        "time" => $diffTime
    );

    echo json_encode($data);
}

?>

And the JavaScript-File:

var $ = jQuery;

function init() {
    $.ajax({
        url: "./myFolder/user.php",
        data: {
            action: "init",
            startTime: new Date().getTime()
        },
        type: "post",
        success: function (output) {
            var data = $.parseJSON(output);
            var counter = data.counter;
            var max = data.max;
            var startTime = data.startTime;

            console.log("StartTime: " + startTime);
        }
    });
}

function check() {
    $.ajax({
        url: "./myFolder/user.php",
        data: {
            action: "check",
            endTime: new Date().getTime()
        },
        type: "post",
        success: function (output) {
            var data = $.parseJSON(output);
            var time = data.time;

            console.log("Time: " + time);
        }
    });
}

That's all i do and the $private_startTime is always null in the php check($endTime) function.

Is my User Session working correct? Cause if i do:

global $private_id;

and give it back within my json data it is also null.

Mulgard
  • 9,877
  • 34
  • 129
  • 232
  • When, and how many times do you call `init()` and `diff()`? Make sure you don't change `$private_startTime` in a third function. – klenium Jul 19 '15 at 12:59
  • It's probably not great practice either but a better way to do this might be to create a static object with attributes matching your global variables. – Parris Varney Jul 19 '15 at 13:02
  • When you run `check()` from your js, your php won't call `init()`, hence `$private_*` will be `null`. If you make 2 ajax requests, your server won't remember to the variables. You need to call `init()` each time if you want to give them values. Or change your code. Or you can use [Memcache](http://php.net/manual/en/book.memcache.php). – klenium Jul 19 '15 at 13:25
  • 1
    Sessions and variables are different things. Variables are always lost when your program finishes the work. Sessions are stored in your server, in a file or database, and you can read back them later. If you want to store a value in the session, use `$_SESSION["name"] = $var`. See the [documentation](http://php.net/manual/en/session.examples.basic.php) – klenium Jul 19 '15 at 13:28
  • Why did you delete all your comments...? – klenium Jul 19 '15 at 13:52

3 Answers3

2

Global variables don't persist across requests, you're supposed to use sessions for that and session variables are accessed and modified using $_SESSION:

function init($startTime) 
{
    $_SESSION['private_counter'] = 1;
    $_SESSION['private_max'] = 15;
    $_SESSION['private_startTime'] = $startTime;

    $data = array(
        "counter" => $_SESSION['private_counter'], 
        "max" => $_SESSION['private_max'],
        "startTime" => $_SESSION['private_startTime'],
    );

    echo json_encode($data);
}

function check($endTime) 
{
    $diffTime = $endTime - $_SESSION['private_startTime'];

    $data = array(
        "time" => $diffTime
    );

    echo json_encode($data);
}
Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
1

No, they won't get redefined. Run this test code, and you'll see:

<?php
function diff() {
    global $private_startTime;
    var_dump($private_startTime);
}
function init($startTime) {
    global $private_startTime;
    $private_startTime = $startTime;
    var_dump($private_startTime);
}
$private_startTime = 0;
init(1437309883114);
diff();
var_dump($private_startTime);
?>

It prints 1437309883114 3 times. The problem is in your code, which we can't see. The global keyword doesn't affect the value of the varible. From the documentation:

By declaring $a and $b global within the function, all references to either variable will refer to the global version.

klenium
  • 2,468
  • 2
  • 24
  • 47
0

You can use $GLOBALS directly. PHP $GLOBALS array.

koredalin
  • 446
  • 3
  • 11
  • [They're the same.](http://stackoverflow.com/questions/8035355/what-is-the-difference-between-globals-and-global) – klenium Jul 19 '15 at 13:35
  • I have some issues with the `global` keyword sometimes. I prefer to go around it. And of course direct access to the global scope varibales from any where is not a good practice. – koredalin Jul 19 '15 at 13:48
  • I work on custom framework on my work. I have no permissions to show this code. – koredalin Jul 19 '15 at 13:55
  • I like your example Klenium. I will use the 2 methods, when I need them. – koredalin Jul 19 '15 at 13:58