user4013835
user4013835

Reputation:

How to use $GLOBALS to share variables across php files?

I have a file, index.php that produces a link to a page that I want my user to only be able to access if some $var == True.

I want to be able to do this through the $GLOBALS array, since my $_SESSION array is already being filled with instances of a specific class I want to manipulate further on.

My index.php page:

<?php

    $var = True;

    $GLOBALS["var"];

    echo "<p><a href='next.php'>Click to go to next page</a></p>";

?>

My next.php page:

<?php

        if($GLOBALS["var"] == False)
            exit("You do not have access to this page!");
        else
            echo "<p>You have access!</p>";

?>

Currently, next.php is echoing the exit text. Am I accessing/assigning to the $GLOBALS array correctly? Or am I not using it properly?

Thanks!

EDIT: So I've tried some of the suggestions here. This is my new index.php:

<?php

    $GLOBALS["var"] = True;

    echo "<p><a href='next.php'>Click to go to next page</a></p>";

?>

My next.php:

<?php

    if($GLOBALS["var"] == False)
        exit("You do not have access to this page!");
    else
        echo "<p>You have access!</p>";

?>

However, I'm still running into the same issue where the exit statement is being printed.

Upvotes: 1

Views: 5679

Answers (1)

EternalHour
EternalHour

Reputation: 8661

It's much better to use sessions for this, since they are more secure and exist for this purpose. The approach I would recommend, is starting a new separate session array.

session_start();
$_SESSION['newSession']['access'] = true;

Then to access it use the same key/value.

Upvotes: 4

Related Questions