PHP pass variable to include

159,293

Solution 1

You can use the extract() function
Drupal use it, in its theme() function.

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

function includeWithVariables($filePath, $variables = array(), $print = true)
{
    $output = NULL;
    if(file_exists($filePath)){
        // 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) {
        print $output;
    }
    return $output;

}


./index.php :

includeWithVariables('header.php', array('title' => 'Header Title'));

./header.php :

<h1><?php echo $title; ?></h1>

Solution 2

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

Solution 3

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).

Solution 4

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.

Solution 5

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'];
Share:
159,293
user1590646
Author by

user1590646

Updated on November 15, 2020

Comments

  • user1590646
    user1590646 over 3 years

    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!