Recently Posted

Feb
17


Passing variables to a PHP include file

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]

9 Responses to “Passing variables to a PHP include file”

  1. PHPman said on March 27th, 2007 at 8:38 pm:

    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”);

  2. Voodoochilli said on April 1st, 2007 at 6:40 pm:

    Yes, that works.

  3. Voodoochilli said on April 7th, 2007 at 9:57 am:

    Just re-read that. $123 would need to be defined before calling the include file.

  4. hmldit said on April 14th, 2007 at 7:18 pm:

    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.

  5. Admin said on April 16th, 2007 at 9:12 am:

    Interesting, cheers.

  6. Alex said on April 17th, 2007 at 1:33 am:

    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!

  7. Alex said on April 17th, 2007 at 1:35 am:

    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; ?]

  8. Voodoochilli said on April 17th, 2007 at 9:06 am:

    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?

  9. Voodoochilli said on April 17th, 2007 at 11:14 am:

    I guess another way of passing it would be using a session variable. Not ideal, but it would work.

Leave a Reply