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.
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");
Sorry if my question is not clearly understandable, I don't know how to express well what I want to say in English.
This is not a problem with code per se, as it is working as shown, but mostly a doubt of the behaviour of PHP.
When I call a function from another php file, it seems to read the function itself i.e. function loademp(){}
however, if I access the file containing the function from an ajax, it seems to need a call to the function i.e loademp() to be in the same file.
Since I had this issue I ended having this code in order to make it work from both origins, with the call for the ajax inside an if condition, otherwise it would be called twice from the php file:
<?php
if ($_POST['runFunct']=="loademp"){ //call from ajax needs 'loademp()' to access the function;
loademp();
}
function loademp(){ //loaded from another file apparently.
try{
//PDO code
print_r(json_encode($results));
}catch(PDOException $e){
echo $e;
}
}
My other file just look like this:
require __DIR__.'loademp.php';
loademp();
Isn't there a more practical way to just use the code for both cases with no conditioning depending on the origin? Since I can't call a specific function from ajax without the use of POST variables, I guess this is the best case for it, but I would appreciate if you could point out the good practices about it.
I think your confusion here is between defining a function and executing a function.
To define a function, you write something like this:
function say_hello_world() {
echo "Hello, World!\n";
}
This doesn't cause anything to happen immediately, it just defines how to do something. In this case, it's basically like saying:
Whenever I ask you to "say hello world", output to the screen "Hello, World!\n"
To make something actually happen, you have to execute the function, which looks like this:
say_hello_world();
That's basically saying:
Do the actions I gave you for "say hello world"
In your example, your file 'loademp.php' defines a function called loademp - it says "whenever I ask you to 'loademp', here's what I want you to do". In your other file, you include that file, so the function is defined. Then, you run it with this line:
loademp();
An AJAX call is no different from any other page load, so you need to do the same thing there - first, define the function, or include the file that does; then, execute the function.
So, rather than calling loademp.php directly, you could call a PHP script like define_and_execute_loademp.php with exactly the lines you've mentioned:
require __DIR__.'loademp.php';
loademp();
Without use of cookie, session, post, get superglobals, is there a way to retrieve variables between php files?
1.php has
$value="hello";
and
2.php wants to retrieve
$value // with value hello
TRY this:
1.php
$a="this is my 1.php";
2.php
include("1.php");
echo $a;
OUTPUT:
this is my 1.php
Here's an example using a class...
1.php
<?php
class Config {
public static $test = "hello world!";
public static $arrayTest = array(
'var1'=>'hello',
'var2'=>'world',
);
}
?>
2.php
<?php
include('1.php');
echo Config::$test;
echo Config::$arrayTest['var1'];
?>
You will have to store the state of the variables somewhere. If you don't want to use the session, you can write them to a file or database. Or, you can store them client-side using JavaScript. You can't read between two different requests without storing the information, though.
Here is a common method I use, because you can write to it as well, making it dynamic and not hard coded values that require you to manually edit the file.
globalvalues.php
<?
return array (
'value1' => 'Testing'
);
2.php
$globalValues = include('globalvalues.php');
echo $globalValues['value1'];
I have wrapper classes around this, but thats the basics of it.
You could make a class, then include the class and reference the variables through that class.
If they are run in the same call, then you can include the PHP file that defines the variable in the second PHP file and access it as if it was defined in the second one.
If these scripts are executed as part of 2 different calls, then you need to give us more information about what / why you are trying to do.
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.
Let's assume we have the following structure:
index.php
config.inc.php
\ lib
\ lib \ common.php
Several parameters like database name, user & co are configured in config.inc.php. What is the proper way to access them i.e. from a function located in \lib\common.php. Do I really have to do an include_once("config.inc.php") within each function there?
It doesn't seem to work if:
config.inc.php is included once once in index.php, before including \lib\common.php there
if config.inc.php defines all variables before including \lib\common.php and all other files (this way I would only have to include config.inc.php in all "central" files at the level of index.php
neither does it work if config.inc.php is included at the top of \lib\common.php
Many thanks - I wasn't able to find a solution with Google!
Solution
I included config.inc.php once in index.php (as suggested by Galen) and used global (as suggested by David). Everything is working as I would expect it, many thanks!
Later on I will definitely look into auto_prepend as suggested by n3rd, tkx for that as well!
You have to use the global keyword to access variables which were defined outside of a function:
$var1 = "muh";
$var2 = "foo";
function test() {
global $var1;
echo "var1=$var1; var2=$var2\n";
}
will print "var1=muh; var2=".
You simply do:
include_once("..\\config.inc.php");
at the top of common.php.
Now there are a few things here - first the backslashes are annoying, and you can (even on windows, exchange them for forward slashes ("../config.inc.php"). If you have the directory where config.inc.php is contained within in your include path, you can even just do "config.inc.php".
Last and not least, if the data in config.inc.php is required for common.php to work, i suggest you switch to require_once() instead, as that will cause a call to exit() or die() in case the file fails to be included, hence stopping further execution.
EDIT: Ah I didn't spot what others said. To use variables that are declared outside of a function inside of a function, you need to let the function know that it needs to "pull" these variables inside the function scope by using the global keyword (as other have said).
Consider the following example:
$var = "Hello World";
function changeVar(){
$var = "Bye World!";
echo $var . "\n";
}
changeVar();
echo $var;
The output of above stated code, is NOT:
Bye World!
Bye World!
but rather:
Bye World!
Hello World
This is due to the fact that the $var INSIDE of the function is its own variable, different from the $var defined OUTSIDE of the function. Change this to:
$var = "Hello World";
function changeVar(){
global $var;
$var = "Bye World!";
echo $var . "\n";
}
changeVar();
echo $var;
And now you have the expected output:
Bye World!
Bye World!
If you include config.inc.php in the index.php file...all files that are included after it will be able to use the data inside it.
If you have functions in common.php you'll have to use the global keyword, or pass the data as arguments, in order to access the data in config.inc.php
U use the auto_prepend feature to do exactly that. The prepended file then searches up the directory hierarchy from the current script and looks for files ending with '.autoinc.php' and includes them in reverse order, i.e. the ones in subdirectories can overwrite stuff defined in files further up the hierarchy. This is set up once and works automatically everywhere and is entirely unobtrusive. I find this to be a rather beautiful and universal solution.
IMHO that's not a good practice to define variables in configurational purposes. You can rewrite them inside your code. Better define constants. As a benefit - they are in global scope and you can use them from anywhere without "global" keyword.
I usually use an abstract Config class with static methods, which parses external data (I use XML config files outside the DOCUMENT_ROOT) and then provides it, casted to objects, with code like this
$dbalias = Config::get('db');
DB::connect($dbalias);
echo $dbalias->user . '#' . $dbalias->host;
It is very useful when you work with team and use versioning tool (like SVN). Evereyone in your team work on localhost an commit everything but local config file which is not being versioned.
Not sure, that this way is the best, but safe and very comfortable to code, to read and to support.