Pass value to include file in php

How to pass parameter to included file? I tried the following, but that did not work.

include "myfile.php? var = 123";

and in myfile.php, I am trying to get a parameter using $ _GET ["var"].

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

for this i also did this:

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

Any clues? Thanks.

+2
source share
4 answers

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

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

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, and not its php code? Consider the following:

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

virtual can also work

+4
source

Create the function for which they are intended:

included.php

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

file.php

 <?php require_once 'included.php'; doFoo('some argument'); 
+1
source

The code in the attached files runs in the same area as the containing file.

It:

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

This is for most purposes and goals exactly the same as:

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

All Articles