I just had the strangest problem to debug…hope someone can explain to me why the problem was happening.
I was including a file. And depending on how it got included messed up availability of variables for stuff happening in the included file. Here’s what I mean…
Result: ‘includedfile.php’ gets included, but somehow $testvar is not available to it (ie. a line of code: echo $testvar; in ‘includedfile.php’ does not output anything).
Can anyone shed some light on why this is happening??
upon further investigation, what seems to make the actual difference is the following:
say my domain is mysite.com with the site main directory being /home/mysite/
$baseDomain = 'mysite.com';
$basePath = '/home/mysite/';
$testvar = 'homeo';
$filetoinclude1 = $baseDomain.'filetoinclude.php';
$filetoinclude2 = $basePath.'filetoinclude.php';
include($filetoinclude1); // includes the file, but $testvar is not available
include($filetoinclude2); // includes the file, and $testvar is available
The $filetoinclude1 would have (if I echo the statement) ‘myseite.com/filetoinclude.php’, and the code gets included…but I’m not sure what happens with the variable scope and why no variables previously defined are available?
The only major is that include() will parse the contents of the file (or resource in this case) looking for an opening <?php tag. If it finds one, it’ll start parsing the text as PHP.
What’s happening in the first example I gave above, is PHP is including a file from your web server, but it’s doing so via HTTP. So it’s hitting requesting the page through apache (assuming that’s you’re web server). What apache returns is the already processed script, rather than the source code.
So if myscript.php looked like this…
<?php
$myVar = 'something';
echo 'Hello!';
If it was included over http in another script like this (will call this script index.php)…
include 'http://mydomain.com/myscript.php';
All index.php will get back is the string ‘Hello!’.
This is all assuming that the variable in your example is actually…
$baseDomain = 'http://mydomain.com';
I can’t thing of anything else that could be causing this.
If it helps for further reference, the include() documentation page mentions the following:
you can specify the file to be included using a URL … instead of a local pathname.
Followed by:
This is not strictly speaking the same thing as including the file and having it inherit the parent file’s variable scope; the script is actually being run on the remote server and the result is then being included into the local script.