Mulgard
Mulgard

Reputation: 10569

PHP: Variables get redefined when using global?

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.

Upvotes: 0

Views: 155

Answers (3)

Ja͢ck
Ja͢ck

Reputation: 173532

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);
}

Upvotes: 2

koredalin
koredalin

Reputation: 445

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

Upvotes: 0

klenium
klenium

Reputation: 2607

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.

Upvotes: 1

Related Questions