I am trying to use a global in a file that is just used to post data to. The global is not being registered on that page. How can I get the globals accessible in that page.
EDIT maybe I wasnt too clear so let me clear it up. I have these files
index.php
global $user;
echo $user->uid;
post.php
global $user;
echo $user->uid;
now from index.php I am posting to post.php through jquery. However when I echo $user->uid from post.php it is not echoing but when I echo it from index.php it is showing it. How can I get that $user->uid accessible from post.php.
You have to remember that when the user submits the form and redirect to
post.php
, the variables inindex.php
are long gone. PHP executions are short-lived unlike normal desktop applications.Whatever you do in
index.php
to get the$user
object must be repeated inpost.php
. If you don't want to replicate the code, just put it in some fileinit_user.php
and have bothindex.php
andpost.php
include the file usinginclude_once('init_user.php');
I think you should be looking into sessions rather than globals. From what it sounds like, you are registering a variable on one page, then when the user moves to another page, you want that variable to be usable.
Sessions will let you do that. Simply use this code:
And on subsequent pages...
Which will output
foo
.http://www.php.net/manual/en/book.session.php
if you need a global inside a function do like this
reference about scoping
for superglobals like
$_POST
,$_GET
(etc...) they are available anywhere.from your updated question, you cannot share variable between two different call of PHP. you would have :
more reference about how PHP play with session there
I agree with mattbasta, globals were disabled by security reasons. You can use it anyway but the right way is to use session.
Other thing is, you said: "now from index.php I am posting to post.php through jquery." Are you using some Ajax call? If not I don't understand why use JS to do this... If you are sending the data through Ajax and only want to send this param try this:
And then handle it from your ajax call like:
Hope this help you.
Another way to access variables from the global scope is to use the special PHP-defined $GLOBALS array.
Example from php.net