how can i create a global php variable that can be accessed from any file?

A value that indicates whether someone is logged in or not would be best stored in the Session – then it will persist between requests to different scripts (by the same user), but not permanently.



When the user has successfully logged in, set a variable

session_start(); //access the session

//...some code here to check username / password etc, and then if they are all ok, you can set them as logged in for the duration of the session....

$_SESSION["loggedin"] = true; //store a variable in the session

Then in home.php, when the user visits this page you can check the session to see if they logged in successfully or not:

$loggedIn = $_SESSION["loggedin"];

//if not logged in, redirect back to the login page and end the script
if ($loggedIn == false) {
  header("Location: login.php");

//otherwise, continue as normal...

There’s a comprehensive explanation of how sessions work here.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top