What is the difference between session variables and global variables in PHP?
Application variable: it is used for entire application which common for all users. It is not for user specific. this variable value will lost when application restarted. Session variable :- this variable is for user specific.
Session variables are special variables that exist only while the user's session with your application is active. Session variables are specific to each visitor to your site. They are used to store user-specific information that needs to be accessed by multiple pages in a web application.
Cookies are client-side files on a local computer that hold user information. Sessions are server-side files that contain user data. Cookies end on the lifetime set by the user. When the user quits the browser or logs out of the programmed, the session is over.
Session variables solve this problem by storing user information to be used across multiple pages (e.g. username, favorite color, etc). By default, session variables last until the user closes the browser. So; Session variables hold information about one single user, and are available to all pages in one application.
Global variables are variables that can be accessed from anywhere in the application, as they have global scope.
Session variables are can also be accessed from anywhere in the application, but they are different for different users, since they depend on the session. They die when a particular user session ends.
global
is just a keyword to access a variable that is declared in the top level scope and isn't available in the actual scope. This hasn't anything to do with the session: do not persist between pages.
$a = "test";
function useGlobalVar(){
echo $a; // prints nothing, $a is not availabe in this scope
global $a;
echo $a; // prints "test"
}
$GLOBALS
is another way to access top-level scope variables without using the global
keyword:
$a = "test";
function useGlobalVar(){
echo $GLOBAL['a']; // prints "test"
}
There's a bit of of confusion between global
and superglobals
: Superglobals (like $GLOBALS, $_REQUEST, $_SERVER) are available in any scope without you having to make a global declaration. Again, they do not persist between pages (with the exception of $_SESSION).
$_SESSION is a Superglobal array that persist across different pages.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With