Question

When I include a page using it's full URL (like include 'http://mysite.tld/mypage.php'), I can't use the $GLOBALS in mypage.php, it returns Undefined index error.

But when I include it using it's relative path (like include 'mypage.php'), then it's OK.

The reason why am I using URL instead of relative path is that I want to include $_GET parameters to mypage.php

Is there any logical explanation of this strange behaviour?


Note that both files are on the same server, in the same directory.

Was it helpful?

Solution

Including files with a URL means the code is run as a separate process, which means it runs under a different variable scope. This is as opposed to if you include the file via a relative path, in which case it is pretty much equivalent to cut and pasting the code into the script.

Essentially this means that the only variables available from your starting script are those that you explicitly pass (as you are in this case using the $_GET variables). This includes the $_SESSION variables, since the caller is your own server rather than the client.

This behaviour is noted in the PHP manual's include page:

If the target server interprets the target file as PHP code, variables may be passed to the included file using a URL request string as used with HTTP GET. 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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top