5

How do you pass a parameter into an include file? I tried the following but it doesn't work.

include "myfile.php?var=123";

and in myfile.php, I try to retrieve the parameter using $_GET["var"].

include "myfile.php?var=123"; will not work. PHP searches for a file with this exact name and does not parse the parameter

for that I also did this:

include "http://MyGreatSite.com/myfile.php?var=123";but it does not also work.

Any hints? Thanks.

1
  • Afaik you cannot include remote files. Commented Apr 15, 2010 at 9:47

4 Answers 4

8

Wrap the contents of the included file in a function (or functions). That way you can just do

include "myfile.php";
myFileFunction($var1, $var2);
Sign up to request clarification or add additional context in comments.

Comments

6

quick and dirty

 $var = 123;
 include "myfile.php";

in myfile just use "$var"

The same but without global variables:

  function use_my_file($param) {
      $var = $param;
      include "myfile.php";
  }

Hold on, are you trying to include the result of myfile.php, not its php code? Consider the following then

  $var = 123;
  readfile("http://MyGreatSite.com/myfile.php?var=$var"); //requires allow_url_fopen=on in php.ini

virtual might also work

1 Comment

I was just about to type that :)
1

Create a function, that's what they are for:

included.php

<?php

function doFoo($param) {
    // do something with $param
}

file.php

<?php

require_once 'included.php';

doFoo('some argument');

Comments

1

Code in included files is executed in the same scope as the including file.

This:

// main.php
$var = 'a';
include 'inc.php';
echo $var;

// inc.php
$var = 'b';

Is for most intents and purposes exactly the same as:

// main.php
$var = 'a';
$var = 'b';
echo $var;

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.