PHP pass variable to include
Asked Answered
K

16

106

I'm trying to pass a variable into an include file. My host changed PHP version and now whatever solution I try doesn't work.

I think I've tried every option I could find. I'm sure it's the simplest thing!

The variable needs to be set and evaluated from the calling first file (it's actually $_SERVER['PHP_SELF'], and needs to return the path of that file, not the included second.php).

OPTION ONE

In the first file:

global $variable;
$variable = "apple";
include('second.php');

In the second file:

echo $variable;

OPTION TWO

In the first file:

function passvariable(){
    $variable = "apple";
    return $variable;
}
passvariable();

OPTION THREE

$variable = "apple";
include "myfile.php?var=$variable"; // and I tried with http: and full site address too.


$variable = $_GET["var"]
echo $variable

None of these work for me. PHP version is 5.2.16.

What am I missing?

Thanks!

Katheryn answered 10/8, 2012 at 15:50 Comment(4)
Did you try denining a constant ?Doublereed
you dont have to pass variables in to include files. your webserver will just load the code of your files when you include them just like if you had written that code from the include file in to your other file.Intuit
Could you clarify 'None of these works'? Error messages will be helpful, too... And, AFAIK, included code is executed within the same context, so global is not necessary; your first option should run just fine.Joleen
As others said, the include() is just like pasting the code there, it continues the execution of the code just like being in same file. You don't have to find a way to include the variable in the include file, you can simply write it before the include() (if needed).Cellule
D
73

Speaking of passing a variable to include, it doesn't need any special action: any php variable defined prior calling include is already available in the included file (given it's available in the scope where include is called). This is exactly how include works.

While in order to pass a set of variables into a function that calls include inside, you can use extract()
Drupal use it, in its theme() function.

Here it is a render function with a $variables argument.

function includeWithVariables($filePath, $variables = array(), $print = true)
{
    // Extract the variables to a local namespace
    extract($variables);

    // Start output buffering
    ob_start();

    // Include the template file
    include $filePath;

    // End buffering and return its contents
    $output = ob_get_clean();
    if (!$print) {
        return $output;
    }
    echo $output;
}

**./index.php :**
includeWithVariables('header.php', array('title' => 'Header Title'));

./header.php :

<h1><?php echo $title; ?></h1>
Dedans answered 8/8, 2017 at 8:48 Comment(3)
You can also use this method adding the EXTR_REFS flag to the extract function (see php.net/manual/en/function.extract.php) so that when you pass a variable with reference: array( 'title' => &$title ) the $title can be changed inside the included file.Antalkali
I don't think this works in later versions of PHP, say 7.3Borroff
It works in (PHP 4, PHP 5, PHP 7, PHP 8), thank you for this answer, should be marked as correct answer.Goldsmith
Q
54

Option 3 is impossible - you'd get the rendered output of the .php file, exactly as you would if you hit that url in your browser. If you got raw PHP code instead (as you'd like), then ALL of your site's source code would be exposed, which is generally not a good thing.

Option 2 doesn't make much sense - you'd be hiding the variable in a function, and be subject to PHP's variable scope. You'ld also have to have $var = passvariable() somewhere to get that 'inside' variable to the 'outside', and you're back to square one.

option 1 is the most practical. include() will basically slurp in the specified file and execute it right there, as if the code in the file was literally part of the parent page. It does look like a global variable, which most people here frown on, but by PHP's parsing semantics, these two are identical:

$x = 'foo';
include 'bar.php';

and

$x = 'foo';
// contents of bar.php pasted here
Quinquereme answered 10/8, 2012 at 15:55 Comment(2)
"Slurp in"? I'm sorry I cannot find a good definition for this!Intercalation
@MattiaRasulo "Slurp" means to read the entire contents of a file and put the whole contents somewhere. Basically, include() copies the included file and pastes its contents in place of the include() function.Emetic
I
14

Considering that an include statment in php at the most basic level takes the code from a file and pastes it into where you called it and the fact that the manual on include states the following:

When a file is included, the code it contains inherits the variable scope of the line on which the include occurs. Any variables available at that line in the calling file will be available within the called file, from that point forward.

These things make me think that there is a diffrent problem alltogether. Also Option number 3 will never work because you're not redirecting to second.php you're just including it and option number 2 is just a weird work around. The most basic example of the include statment in php is:

vars.php
<?php

$color = 'green';
$fruit = 'apple';

?>

test.php
<?php

echo "A $color $fruit"; // A

include 'vars.php';

echo "A $color $fruit"; // A green apple

?>

Considering that option number one is the closest to this example (even though more complicated then it should be) and it's not working, its making me think that you made a mistake in the include statement (the wrong path relative to the root or a similar issue).

Isiah answered 10/8, 2012 at 15:59 Comment(1)
Perhaps I have confused the order of things? The structure is, in fact: main.php $variable = $_SERVER['PHP_SELF']; include = 'side.com/footer.php; footer.php: echo $variable; All the included file doesn't contain the variable, it merely does something to it. In all the options I tried, the output is either blank, or includes $_SERVER['PHP_SELF'] of the footer.php and not the main.php. Is this different?Katheryn
D
7

I have the same problem here, you may use the $GLOBALS array.

$GLOBALS["variable"] = "123";
include "my.php";

It should also run doing this:

$myvar = "123";
include "my.php";

....

echo $GLOBALS["myvar"];

Have a nice day.

Decongestant answered 24/11, 2015 at 9:17 Comment(2)
This answer is self-contradicting. WHY "use the $GLOBALS array", if $myvar = "123"; "also run"?Ramie
Hello Common Sense, user1590646 describes a php configuration where this is not possible.Decongestant
L
7

I've run into this issue where I had a file that sets variables based on the GET parameters. And that file could not updated because it worked correctly on another part of a large content management system. Yet I wanted to run that code via an include file without the parameters actually being in the URL string. The simple solution is you can set the GET variables in first file as you would any other variable.

Instead of:

include "myfile.php?var=apple";

It would be:

$_GET['var'] = 'apple';
include "myfile.php";
Legislate answered 11/1, 2018 at 19:20 Comment(0)
M
5

OPTION 1 worked for me, in PHP 7, and for sure it does in PHP 5 too. And the global scope declaration is not necessary for the included file for variables access, the included - or "required" - files are part of the script, only be sure you make the "include" AFTER the variable declaration. Maybe you have some misconfiguration with variables global scope in your PHP.ini?

Try in first file:

  <?php 
  $myvariable="from first file";
  include "./mysecondfile.php"; // in same folder as first file LOLL
  ?>

mysecondfile.php

  <?php 
  echo "this is my variable ". $myvariable;
  ?>

It should work... if it doesn't just try to reinstall PHP.

Manville answered 22/6, 2019 at 23:23 Comment(0)
A
4

In regards to the OP's question, specifically "The variable needs to be set and evaluated from the calling first file (it's actually '$_SERVER['PHP_SELF']', and needs to return the path of that file, not the included second.php)."

This will tell you what file included the file. Place this in the included file.

$includer = debug_backtrace();
echo $includer[0]['file'];
Acne answered 10/8, 2012 at 15:57 Comment(2)
Based on the OP's comments in his question "The variable needs to be set and evaluated from the calling first file (it's actually '$_SERVER['PHP_SELF']', and needs to return the path of that file, not the included second.php)." He needs to find out what the path is of the file that did the including of second.php.Acne
Noted. (it's not clear from your answer, please clarify it ["since OP wants to get the original file name blah blah blah"]).Nava
T
2

The Option one if tweaked like this, it should also work.

The Original

Option One

In the first file:

global $variable; 
$variable = "apple"; 
include 'second.php'; 

In the second file:

echo $variable;

TWEAK

In the first file:

$variable = "apple"; 
include 'second.php';

In the second file:

global $variable;
echo $variable;
Thunderbolt answered 14/11, 2020 at 13:0 Comment(0)
A
0

According to php docs (see $_SERVER) $_SERVER['PHP_SELF'] is the "filename of the currently executing script".

The INCLUDE statement "includes and evaluates the specified" file and "the code it contains inherits the variable scope of the line on which the include occurs" (see INCLUDE).

I believe $_SERVER['PHP_SELF'] will return the filename of the 1st file, even when used by code in the 'second.php'.

I tested this with the following code and it works as expected ($phpSelf is the name of the first file).

// In the first.php file
// get the value of $_SERVER['PHP_SELF'] for the 1st file
$phpSelf = $_SERVER['PHP_SELF'];

// include the second file
// This slurps in the contents of second.php
include_once 'second.php';

// execute $phpSelf = $_SERVER['PHP_SELF']; in the secod.php file
// echo the value of $_SERVER['PHP_SELF'] of fist file

echo $phpSelf;  // This echos the name of the First.php file.
Aleishaalejandra answered 8/7, 2014 at 18:6 Comment(0)
E
-1

You can execute all in "second.php" adding variable with jQuery

<div id="first"></div>

<script>
$("#first").load("second.php?a=<?=$var?>")
</scrpt>
Emeliaemelin answered 22/6, 2020 at 22:43 Comment(2)
Looping variables through frontend like this is a code-smell and should be avoided.Bonaire
@Jonas Stensved, why? Give me a link with explicationEmeliaemelin
W
-1

An alternative to using $GLOBALS is to store the variable value in $_SESSION before the include, then read it in the included file. Like $GLOBALS, $_SESSION is available from everywhere in the script.

Willowwillowy answered 18/5, 2022 at 23:36 Comment(0)
O
-1

Pass a variable to the include file by setting a $_SESSION variable

e.g.

$_SESSION['status'] = 1; include 'includefile.php';

// then in the include file read the $_SESSION variable

$status = $_SESSION['status'];

Ohare answered 25/9, 2022 at 10:38 Comment(0)
M
-1

Try adding this:

$_GET['varable']; // from your URL or anything
include "adminchat.php";

This will directly pass the variable data to any links or command written in other file.

Meninges answered 30/4, 2023 at 19:28 Comment(0)
S
-2

This worked for me: To wrap the contents of the second file into a function, as follows:

#firstFile.php

<?php
    include "secondFile.php";

    echoFunction("message");

#secondFile.php

<?php
    function echoFunction($variable)
    {
        echo $variable;
    }
Szczecin answered 19/11, 2017 at 17:7 Comment(0)
P
-3

I found that the include parameter needs to be the entire file path, not a relative path or partial path for this to work.

Pathoneurosis answered 21/7, 2016 at 19:23 Comment(1)
No, that is incorrect. Relative paths work just fine in include's. You just have to be sure you are assuming a correct "relative to what" beginning.Miranda
N
-4

Do this:

$checksum = "my value"; 
header("Location: recordupdated.php?checksum=$checksum");
Nailbrush answered 27/2, 2015 at 0:18 Comment(2)
While this may answer the question it’s always a good idea to put some text in your answer to explain what you're doing. Read how to write a good answer.Arrow
Some explanation would be great.Jepson

© 2022 - 2025 — McMap. All rights reserved.