[php] PHP pass variable to include

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!

This question is related to php variables include global-variables global

The answer is


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

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


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.


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


I know this is an old question, but stumbled upon it now and saw nobody mentioned this. so writing it.

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;

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>

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;
    }

Do this:

$checksum = "my value"; 
header("Location: recordupdated.php?checksum=$checksum");

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";

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

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

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

<script>
$("#first").load("second.php?a=<?php echo $var?>")
</scrpt>

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.

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.


Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to variables

When to create variables (memory management) How to print a Groovy variable in Jenkins? What does ${} (dollar sign and curly braces) mean in a string in Javascript? How to access global variables How to initialize a variable of date type in java? How to define a variable in a Dockerfile? Why does foo = filter(...) return a <filter object>, not a list? How can I pass variable to ansible playbook in the command line? How do I use this JavaScript variable in HTML? Static vs class functions/variables in Swift classes?

Examples related to include

"Multiple definition", "first defined here" errors Warning: require_once(): http:// wrapper is disabled in the server configuration by allow_url_include=0 Include PHP file into HTML file Cannot open include file with Visual Studio How to make Apache serve index.php instead of index.html? Include php files when they are in different folders Already defined in .obj - no double inclusions What's the difference between including files with JSP include directive, JSP include action and using JSP Tag Files? What is the correct syntax of ng-include? Visual Studio can't 'see' my included header files

Examples related to global-variables

What is the best way to declare global variable in Vue.js? How do I turn off the mysql password validation? How to declare Global Variables in Excel VBA to be visible across the Workbook How to create a global variable? global variable for all controller and views How to define global variable in Google Apps Script How to modify a global variable within a function in bash? Using a global variable with a thread Is it possible to use global variables in Rust? How to access global js variable in AngularJS directive

Examples related to global

How to access global variables Passing Variable through JavaScript from one html page to another page Change Button color onClick Can I make a function available in every controller in angular? How to declare a global variable in php? PHP pass variable to include Global Git ignore Passing a variable from one php include file to another: global vs. not Ruby on Rails: Where to define global constants? JavaScript: Global variables after Ajax requests