0

I'm studing php and I've read this (important words are bold):

Superglobals — Superglobals are built-in variables that are always available in all scopes These superglobal variables are:

  • $GLOBALS
  • $_SERVER
  • .........

In file1.php I do:

$GLOBALS["ZZZ"] = 555;

Then I have to send file2.php to client, so here, in file1.php I do:

header("Location: /file2.php");

Now I want to retrive my global variable from the global array in file2.php. I do:

echo "My global = ".$GLOBALS["ZZZ"].";";

And I get emptyness... What do I do wrong? Is $GLOBALS really global or it is new after redirection? Thank you in advance.

Max Kurtz
  • 448
  • 5
  • 17
  • 6
    $GLOBALS is set per request afaik, you maybe want to use sessions? Or whatever other persistent storage. – Jonnix Apr 03 '19 at 14:02
  • 1
    If you want something to exist across requests, you need to save it somewhere, maybe `$_SESSION` – Ruan Mendes Apr 03 '19 at 14:02
  • 1
    Its only GLOBAL for the life time of the execution of a Single script. You should look at using the SESSION – RiggsFolly Apr 03 '19 at 14:03
  • I've already used sessions and succeeded, but this message confuses me: Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at ...... – Max Kurtz Apr 03 '19 at 14:03
  • 1
    Every new request in PHP starts from scratch. What that quote means it that you can access those variables in any scope (functions, classes etc), but they will still only exist for that specific request. When you redirect the user, then PHP will start from scratch again. – M. Eriksson Apr 03 '19 at 14:05
  • 3
    For your session_start warning see -> https://stackoverflow.com/questions/8028957/how-to-fix-headers-already-sent-error-in-php – Jonnix Apr 03 '19 at 14:05
  • Ok guys, I've got it! Thanks! Wrong (unclear) documentation here: https://www.php.net/manual/en/language.variables.superglobals.php NOT ALWAYS, but only before next request. – Max Kurtz Apr 03 '19 at 14:07
  • No, the documentation is correct. The `description` part is more concise `Several predefined variables in PHP are "superglobals", which means they are available in all scopes throughout a script. There is no need to do global $variable; to access them within functions or methods.` I.e. available in all your script's scopes, so you can use it anywhere in code and it will be available. – Jonnix Apr 03 '19 at 14:12
  • I was confused by word "always". I tried to find something like window.localStorage, something that is really accessible from anywhere in any time. Now using SESSION blocks my code where I use echo. Backend isn't easy :-) – Max Kurtz Apr 03 '19 at 14:23
  • PS: done my taks with session_start(); Thank the community – Max Kurtz Apr 03 '19 at 14:42

0 Answers0