GLOBALS value being reset

I am building a web application which consists of a number of php scripts linking to each other. The general flow is as follows:

index.php
loats init.php (require_once, which initialises global variables including $GLOBALS[‘maggot’][‘formToken’] => ‘not set yet’
loads Header.html

loads footer.html
I then select the Register link which runs register.php
loads loats init.php (require_once) which I assume doesn’t happen because it is already loaded
checks $_POST and processes any data
generates a new formToken and sets the global variable (see above) - this works as I echo the global variable value
output the form
user updates the form and it is submitted back to register.php

HOWEVER - when register.php processes the form data the global variable has been reset to the original value (and so my token check fails). Why would the global variable $GLOBALS[‘maggot’][‘formToken’] be reset to the value in init.php when register.php is reloaded?

I am obviously misunderstanding something about $GLOBALS and/or require_once(). Some help would be much appreciated.

Web servers are stateless. They don’t know or care about anything outside of the current request. All php resources/variables are destroyed when the script on any page request ends. Any required file is per instance of the script requiring the file.

If you need to maintain state between requests, you would store values in session variables.

Next, don’t use php’s $GLOBALS or the global keyword to get values into functions. You will end up with spaghetti code/variables that will make more work for you to keep track of and find problems when something doesn’t work.

Thank you for your help. I have in fact discovered that I should have been using $_SESSION and not $GLOBALS.

Sponsor our Newsletter | Privacy Policy | Terms of Service