PHP Ferrari
PHP Ferrari

Reputation: 15616

Pass value to an include file in php

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.

Upvotes: 5

Views: 13240

Answers (4)

Bart van Heukelom
Bart van Heukelom

Reputation: 44094

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;

Upvotes: 1

user187291
user187291

Reputation: 53940

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

Upvotes: 6

Ionuț G. Stan
Ionuț G. Stan

Reputation: 179119

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

Upvotes: 1

Yacoby
Yacoby

Reputation: 55445

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

include "myfile.php";
myFileFunction($var1, $var2);

Upvotes: 8

Related Questions