PHP: How to access $GLOBALS variable from different file?

1.4k views Asked by At

I've been trying to set a variable when the index page loads and then access it later in a .php file, but I cannot get it to work. I've tried using global variables and the superglobal $GLOBALS, but I did not succeed.

Here is a simplified version of what I've tried using superglobals:

index.php:

<html>
<body>
    <?php 
        $GLOBALS['a'] = 5;
    ?>
    <div id="myDiv"></div>
</body>


<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>

<script type="text/javascript"> //set the content of the "myDiv" 
        $.ajax({
            url:"functions.php", 
            success:function(result){
                $("#myDiv").html(result);}})
</script>

functions.php file:

<?php
    echo $a;
?>
//got error: Notice: Undefined index: a in C:\xampp\htdocs\function.php on line 2.

I've also tried modifying functions.php to:

<?php
    echo $GLOBALS['a'];
?>

But I got the same error.

Is it just a simple error or am I missing the whole point of global variables?

Obs1.: In the actual application, I am trying to execute a function that reads a csv file and loads it as an array into memory, which needs to be accessible later.

Obs2: I am using XAMP 3.2.2

1

There are 1 answers

1
nithinTa On

If my understanding is correct you are trying to access a variable in one request which is declared in another request. The index.php you are calling and ajax request you are making to function.php are different http requests. You need to use $_SESSION for this purpose or you might include the declaration file in function.php itself.