I have a file, lets say it's index.php where the very beginning of the file has an include for "include.php". In include.php I set a variable like this:
<?php $variable = "the value"; ?>
then further down the in index.php I have another include, say "include2.php" that is included like this:
<?php include(get_template_directory_uri() . '/include2.php'); ?>
How can I call the "$variable" that I set in the first include, in "include2.php"?
The exact code that I am using is as follows:
The very first line of the index.php I have this line
<?php include('switcher.php'); ?>
Inside switcher.php I have this
<?php $GLOBALS["demo_color"] = "#fffffe"; ?>
If I use this in index.php, it works
<?php echo $GLOBALS["demo_color"]; ?>
However, If I use the following code to include another php file
<?php include(get_template_directory_uri() . '/demo_color.php'); ?>
then inside demo_color.php I have this code:
<?php echo "demo color:" . $GLOBALS["demo_color"]; ?>
The only thing it outputs is "demo color:"
edited for code-formatting
It simply can be used in include2.php, unless the inclusion of include.php happens inside of a different scope (i.e. inside a function call). see here.
If you want to be completely explicit about the intention of using the variable across the app, use the $GLOBALS["variable"] version of it's name, which will always point to the variable called variable in the global scope.
EDIT: I conducted a test against php 5.3.10 to reconstruct this:
// index.php
<?php
include("define.php");
include("use.php");
// define.php
$foo = "bar";
// use.php
var_dump($foo);
This works exactly as expected, outputting string(3) "bar".
<?PHP
//index.php
$txt='hello world';
include('include.php');
<?PHP
//include.php
echo $txt; //will output hello world
So it does work. Though there seems to be a bigger issue since this is likely to be difficult to maintain in the future. Just putting a variable into global namespace and using it in different files is not a best practice.
To make the code more maintainable it might be an idea to use classes so you can attach the variables you need explicit instead of just using them. Because the code around is not showed it is not clear what is your exact need further but it will be likely the code can be put in classes, functions etc. If it is a template you could think about an explicit set() function to send the variable data to the templates and extract() it there.
edit:
In addition based on the information first set your error_reporting to E_ALL and set the display_errors to 1. So you get all errors since the information you placed in your updated question gives indications that a missing variable is used as a constant which should raise errors all over the place.
Related
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!
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>
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
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 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.
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 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.
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 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;
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.
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.
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'];
You can execute all in "second.php" adding variable with jQuery
<div id="first"></div>
<script>
$("#first").load("second.php?a=<?=$var?>")
</scrpt>
I found that the include parameter needs to be the entire file path, not a relative path or partial path for this to work.
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");
In my web page, I wrote:
<?php
//define('__PUBLIC__', $_SERVER['DOCUMENT_ROOT'].'/public');
$doc_public = $_SERVER['DOCUMENT_ROOT'].'/public';
echo "Before include...<==============>$doc_public";
?>
<?php require_once($doc_public.'/inc/head.php'); ?>
<?php echo "After include...<==============>$doc_public"; ?>
And the page shows:
This firstly happened when I notice the fatal error in the footer, but the head is fine.
Although I can implement define or constant variable to avoid this, I am still curious how it happens.
P.S.: I run this under Apache with a port 8001. This is set in 【apache\conf\extra\httpd-vhosts.conf】. I am running more than one webapp under this site. I just share this information, as I am not sure this has anything to do with this case.
Thanks!
When you require a file, if a variable is modified it affects the original script as well, that's how it's designed. Require doesn't create a secondary environment separated from the including file, it just adds the PHP code in sequence, exactly like if you had written the code in the initial file.
Have a look at the official PHP documentation, the first example is exactly the same as your case
http://php.net/manual/en/function.include.php
(include is the same as require, the latter just throws an error. For more info about differences between include and require http://php.net/manual/en/function.require.php)
How does include('./code.php'); work? I understand it is the equivalent of having the code "pasted" directly where the include occurs, but, for example:
If I have two pages, page1.php and page2.php, of which I would need to manipulate different variables and functions in ./code.php, does include() create a copy of ./code.php, or does it essentially link back to the actual page ./code.php?
See the manual.
If you include a text file, it will show as text in the document.
include does not behave like copy-paste:
test.php
<?php
echo '**';
$test = 'test';
include 'test.txt';
echo '**';
?>
test.txt
echo $test;
The example above will output:
**echo $test;**
If you are going to include PHP files, you still need to have the PHP tags <?php and ?>.
Also, normally parentheses are not put after include, like this:
include 'test.php';
Basically, when the interpreter hits an include 'foo.php'; statement, it opens the specified file, reads all its content, replaces the "include" bit with the code from the other file and continues with interpreting:
<?php
echo "hello";
include('foo.php');
echo "world";
becomes (theoretical)
<?php
echo "hello";
?>
{CONTENT OF foo.php}
<?php
echo "world";
However, all this happens just in the memory, not on the disk. No files are changed or anything.
It depends on how you include the code.php file. If you include the code.php file into page1.php and then page2.php then you will have access to it's vars and it would effecitvely just "copy and paste" (beaware that is just used to make it easier to understand since the actual dynamics of that are explained above) the file in however if you link like:
[code.php]
include('page1.php');
include('page2.php');
Then code.php will have access to all of the variables within page1.php but:
page1.php will not have access to vars in code.php
page2.php will not have access to vars in code.php
So in order to inherit the funcitonality of code.php inot both page1.php and page2.php be sure to do something like:
[page1.php]
include('code.php');
[page2.php]
include('code.php');
Then it will work as you expect. So just something to remember there.
Include does not behave like copy paste.
Here is a demonstration using PHP Strict Type Declarations
<?php
// function.php (file)
declare (strict_types = 1);
function sum(int $a, int $b)
{
return $a + $b;
}
/**
* This will throw TypeError:
*/
// echo sum(5.2, 5);
However, if I call this function from an external file
<?php
// caller.php (file)
require_once 'function.php';
/**
* This will Work instead of throwing a TypeError:
*/
echo sum(5.2, 5);
Strict types are enabled for the file that the declare statement was added (function.php)
It does not apply for any function calls made from an external file (caller.php)
because PHP will always defer to the caller when looking to evaluate strict types.
Require doesn't work like copy/paste
For further understanding,
Short answer on how PHP script is Executed &
A more comprehensible explanation on what include/require really does in php
include('./code.php'); // The Same As Pasting The Code From Code.PHP.
It Will Not Redirect To Code.php In Any Case.
I include a PHP file to the HEADER of my WordPress site, which searches through a CSV file and returns me the variable I need. I am trying to have it included in the header because it's a variable I will need throughout the site later on. If I test it out and try to echo this variable from the included script, it works fine. However, in the rest of the site, if I try to call that variable it doesn't return anything.
I know that the variable is being created because I try to echo it and it works. But when the I try to use that variable from a different script, it doesn't work. Is there some kind of code I need to pass the variable over to the rest of the site?
Variables default to function level only, you have to pass them or globalize them if you want to use them elsewhere. Depending on how your script is laid out, you might make it an object property, in which case it will be available anywhere your object is available and in all methods of that object - another option is to use global $var, but that's a bad idea and bad coding practice - another is to put it into a session using $_SESSION['myVar'] = $var and then call it the same way - yet another way is to pass it through arguments such as $database->getRows($var) and then on the other side "public function getRows ($var)", now you have $var in that function by passing it.
Make sure you global $variable the variable everytime you want to use it in a new function, or even within a new script. This will make sure that the variable is available everywhere that you need it.
3 files:
a.php:
<?php
include("c.php");
var_dump("c is ".$c . " after include()");
function incit(){
include("b.php");
var_dump("b is ".$b . " inside incit()");
}
incit();
var_dump("b is ".$b . " after incit()");
?>
b.php:
<?php
$b="bear";
?>
c.php:
<?php
$c="car";
?>
output looks like this:
string(24) "c is car after include()"
string(24) "b is bear inside incit()"
string(19) "b is after incit()"
so $b is only defined INSIDE the scope of the function while $c on the other hand is "globally" definde.
So you have to watch in what scope you are using the include.
How can defined global variable ($begin) that will be recognized in all php file?
(please dont change the case code only add, because I working on big project that i can only add code)
Case:(problem $begin not recognized in the end of the file)
<?php $begin=time()?>
<div>new name</div>
<?php echo time()-$begin; ?>
Edit:
I have stupid mistake in file, now the code works, thanks
Thanks
It's probably a good idea to set up a configuration file that's stored alongside the scripts you use, and then include that file at the top of every script. For example, this could be the content of a file named config.php at the same directory level as the scripts you're using:
<?php
$begin = time();
?>
You can then add the following line to the top of every PHP file that needs to access the variable:
<?php include 'config.php'; ?>
If you want to make sure you don't use that variable by mistake in a script, you can use the define functionality instead. It works in a very similar way, but it's more permanent. You could put this in the configuration file:
<?php
define('BEGIN', time());
?>
And then any script that has the include mentioned above could simply include this code:
<?php echo time() - BEGIN; ?>
You use, constants as they have global scope.
<?php define('TS_START',time())?>
<div>new name</div>
<?php echo time()-TS_START; ?>
or if you cant do that because of your "large" project. maybe you want to double var it.
<?php $begin = $_begin = $__begin = time()?>
<div>new name</div>
<?php echo time()- ($begin ? $begin : ($_begin ? $_begin : $__begin)); ?>
poor programming though, there's no need for that many vars for one small entity, I would rewrite with define and overwrite all instances of $begin with TS_START
With the example you've given, there's no reason why $begin shouldn't still be valid at the end of the program.
Have you checked that you're not using the name $begin for something else within your program?
Similarly, you may be including some third-party code which uses $begin? Either way, consider changing the variable name you're using to a more unique one.
In the example, all your code is in the global scope. But if your real code uses functions for these, then $begin would be at the function-level scope, so wouldn't be global.
In this case, the quickest option would be to add global $begin; at the top of both functions.