I want to pass a variable defined in an include file, identity.php, to the parent file, which I'll call parent.php. When I include identity.php via it's relative path, the variable is available to the parent.php file. When I include identity.php via it's absolute path (to the application root), it doesn't work. Why is this?
File: identity.php
$g_groupid = 2;
File: parent.php
include('absolute_path_to_identity.php');
echo $g_groupid; //NOTHING!
However...
File: parent.php
include('../../identity.php'); //relative path to include file
echo $g_groupid; //echos 2 as expected
I have verified that identity.php is included in both cases by echoing a "identity file is included message" (from within the identity.php file) which is displayed for both the relative and absolute includes. What could be the cause of this behavior?
Are you sure your absolute path is working?
I had similar issues and I use, in this case, always the full path through DOCUMENT_ROOT
Did you try using realpath() ?
Also, I recommend turning off error reporting if its not on already so you can make sure the file is indeed included, and get some more info on this. Add this on the top of your file :
Hmm, try:
This sounds like your "absolute path" is an URL like
http://www.example.com/folder/identity.php
If that's the case PHP will fetch the code from the web server using HTTP, and so all PHP code will be evaluated before the file is included.This will give the behavior you described with the
echo
troubleshooting as well.An "absolute path" is on the form
/home/user/public_html/folder/identity.php
and is not the same thing as an URL.Consider this:
identity.php
When evaluated by the PHP interpreter this will result in this raw text:
If you include that raw text into parent.php it will behave as if it was raw HTML without any PHP code because there are no
<?php
tags in that raw text. Then consider this identity.php:Which will result in this:
What results do you get in your parent.php now? Is $g_groupid
2
or3
?