Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between session variables & Global variables in php? [closed]

What is the difference between session variables and global variables in PHP?

like image 271
Srividhya Avatar asked Feb 13 '13 07:02

Srividhya


People also ask

What is the difference between session variable and application variable?

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.

What are session variables?

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.

What is the difference between cookies and session variables?

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.

What is session variables explain with example?

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.


2 Answers

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.

like image 142
Smita Avatar answered Oct 07 '22 18:10

Smita


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.

like image 24
T30 Avatar answered Oct 07 '22 16:10

T30