Passing variables to a PHP include file
Posted by Voodoochilli | Posted in Development | Posted on 17-02-2007
Tags: PHP
9
Sadly, this just isn’t possible. You would think you would be able to do the following:
[source: php]
include (“filename.php?variable=123″);
[/source]
But you just can’t. There is an alternative though. You can set the variable just before you include the file, for example:
[source: php]
$variable=123;
include (“filename.php”);
[/source]


In your opinion, will $123 work and transfer as a variable to the include file if $123 is defined?
1. $variable=$123;
2. include (“filename.phpâ€);
Yes, that works.
Just re-read that. $123 would need to be defined before calling the include file.
That’s not entirely true.
I guess a windows based distro of PHP before 4.3.0 will puke on this method of accessing remote files but a linux build or newer windows version will work fine and you can pass URL vars.
If “URL fopen wrappers” are enabled in PHP (which they are in the default configuration), you can specify the file to be included using a URL.
->>> include ‘http://www.veneratedesign.com/addMe.php?var1=bla&var2=34‘
There are other Wrapper methods but I don’t know them off hand.
Interesting, cheers.
I’m having problems doing exactly this…
My mainpage.php file goes like this:
And anotherpage.php goes like this:
This is the string:
When I view mainpage.php, I simply get:
This is the string:
(The variable is not being passed)
Help!
That posted wrongly last time because I used tags, sorry:
mainpage.php:
[?php
$string = 'hello';
include 'anotherpage.php';
?]
anotherpage.php:
[?php echo 'This is the string: ' . $string; ?]
Thats odd! It should work. Out of interest, what kind of server are you using?
Does the content need to be inside an include? Is there maybe another solution?
I guess another way of passing it would be using a session variable. Not ideal, but it would work.