Let's begin with an article on a static page (Test.php) that includes another file full of PHP code (Code.php). Some of the echo values on Code.php are declared on a third file higher up the food chain (Values.php).
Everything works fine - until I take the article out of Test.php, insert it in a database and display it by echoing $Content. Now my include doesn't work, since you can't put PHP includes inside a database. (Or maybe you can, but it's apparently next to impossible, and everyone screams DON'T DO IT!)
I just learned how to use file_get_contents:
$Content = str_replace('<p id="1"', '.file_get_contents($BaseINC."/inc/Test.php").'<p id="1">', $Content);
It works great, except that it only displays static text - no PHP code.
Then I learned how to parse the file, like this:
file_get_contents("http://MySite/Test.php")
It works better. I can echo $Something, as long as $Something is defined in Test.php...
$Something = 'Cool!';
echo $Something;
The problem is that all the echo values that are defined on a separate file (e.g. Values.php) no longer work, apparently because I've removed Test.php from the flow. Is there a way to somehow reconnect Test.php with Code.php so those echo values will regain their values? Or is there some other way to accomplish what I'm trying to do?
For whatever it's worth, most of the missing values are created by a database query. One workaround is to recreate the values based on each page's URL. The irony is that all the scripts I've tried for displaying page URL don't even work; instead, they display the path to Test.php. So I'm really confused.
I tried to illustrate the different ways of including a php file:
<?php
//Test.php
$bar = 'orange'; echo $bar;
<?php
// Example.php
echo file_get_contents("Test.php") // $bar = 'orange'; echo $bar;
echo file_get_contents("http://example.com/Test.php") // orange
// Probably not correct, big security risk https://www.owasp.org/index.php/Code_Injection
include("Test.php") // orange
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");
What I am trying to do is change a variable in fileb from filea. Kind of like using fileb as a config file in a way.
Example:
File A:
require_once "fileb.php";
if($power == 'off') {
exit;
}
if($test1 == 'one') {
echo "The first option is selected";
} elseif($test1 == 'two') {
$power = 'off';
}
File B:
$power = 'on';
So in this example a user id prompted for $test1, if they reply with "one" they get a echo. What I want to do is make it so if they reply with "two" it shuts down the page, and not just for them but for everyone. I am trying to do all of this without using a DB, that would be too easy lol. Thanks for the help!
I am trying to do all of this without using a DB, that would be too easy
There's a reason using a database for this is easy. It's the correct way to accomplish this task. Modifying actual PHP code files is a famously bad idea. (And one that somebody on Stack Overflow has almost weekly, it seems.)
If you include the file as part of the executing code, you can use the variable as any other. This allows you to manipulate the variable in a transient way, but not manipulate the code which creates the variable.
What you're trying to do is persist that changed variable. In order to do that, it needs to be written somewhere outside of the application. Databases are really good for that sort of thing. You could also write to a simple text file (a string of text, structured XML, etc.) though in that case you'll have to manually watch out for concurrent writes and other such errors. (Databases are really good at that too, which makes them ideally suited for multi-thread/multi-user applications like web apps.)
I suppose you could treat the PHP file itself as an editable text file like any other. (Since PHP is, after all, just text.) But, again, that's a really bad idea. For one thing, parsing out exactly the value you want and writing back a change only to that value is going to be very difficult. Also, you run the risk of breaking a file which is treated as executable code which opens up all sorts of potential risks.
Just write to a database, or to a file, or to any other simple data persistence medium outside of the application.
Your fileb is lacking the <?php ... ?> tags. Without those, you "code" is never seen as code. it'll just be treated as plain text.
file b:
<?php
$power = 'on';
file c:
Hello
<?php
$foo = 'world!';
file a:
<?php
include('fileb.php');
echo $power;
include ('filec.php'); // "Hello" is immediately output
echo $foo; // tell PHP to put the $foo var, which will print out "world!"
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.
What is the difference between include() and calling a function in PHP?
For example :
1-
<?php
$foo = '<p>bar</p>';
return $foo;
?>
<html><body><?php echo $foo; ?></body></html>
2-insert above php code in a php file and include()
thanks in advance
include() simply takes the full contents of the file and inserts it in, replacing the include() with the contents of the file.
If you have HTML in the included file, it will be output. If you only have PHP in it, the PHP will be run.
To call a function, the function must be available. If the function is in another file, you will still need to include() or require() that file to have it available.
Generally, including is used to get a set of functions or objects into your running script, so that they can be used, although it can also be used as a standalone page or some bit of HTML, like you posted. In reality, it depends on whether you'd rather have another function on the same script or in a remote script, for aesthetics or organization, whatever your reason.
Functions will usually run a bit faster, as server response time and parsing time may make the include function run a bit slower, but for all intents and purposes you wont notice much. Most of the lag will be due to the fact that a local function will be executed with the page, whereas the include function must execute the page, load another page, and then execute that page as well. If that makes sense.
Just as an addition to the existing answers, you can also do this:
sample.php:
<?php
$foo = include('include_with_return_value.php');
?>
<html><body><?php echo $foo; ?></body></html>
and include_with_return_value.php:
<?php
return '<p>bar</p>';
So, include() files can also have a return value, just like functions.