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.
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");
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
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.
I would like to require a file but also pass GET variables through the url, but when I write:
<?php
require_once("myfile.php?name=savagewood");
?>
I get a fatal error. How would I accomplish this functionality in a different way, such that I don't get a fatal error?
variables will be available as normal you do not have to pass like this.
$name='savagewood';
require_once("myfile.php");
$name will be available in myfile.php
<?php
$getVarsArray = $_GET;
$postVarsArray = $_POST;
/* n number of variables and lines of code*/
include('script-a.php');
?>
Now in script-a.php has access to $getVarsArray and $postVarsArray and if in any case you are in doubt you can use $GLOBALS to access any variable throughout the life cycle of a script. But using global variables is a sin. :)
It is not necessary to pass the variables to the new file, because by including the new file the variables are maintained.
Remember that $ _GET is an array, and it can be modified within the script.
<?php
$_GET['name'] = "savagewood";
require_once("myfile.php");
?>
On this case, $_GET['name'] is accesible from the "myfile.php"
I think I have got a perfect solution to your problem. You can use implode function of PHP. But I would strongly recommend doing Shakti Singh's code.
SOLUTION CODE
echo implode(file('http://path-to-your-site/your-dir/myfile.php?name=savagewood'));
I am creating a custom form building system, which includes various tokens. These tokens are found using Regular Expressions, and depending on the type of toke, parsed. Some require simple replacement, some require cycles, and so forth.
Now I know, that RegExp is quite resource and time consuming, so I would like to be able to parse the code for the form once, creating a php code, and then save the PHP code, for next uses. How would I go about doing this?
So far I have only seen output caching. Is there a way to cache commands like echo and cycles like foreach()?
Because of misunderstandings, I'll create an example.
Unparsed template data:
Thank You for Your interest, [*Title*] [*Firstname*] [*Lastname*]. Here are the details of Your order!
[*KeyValuePairs*]
Here is the link to Your request: [*LinkToRequest*].
Parsed template:
"Thank You for Your interest, <?php echo $data->title;?> <?php echo $data->firstname;?> <?php echo $data->lastname;?>. Here are the details of Your order!
<?php foreach($data->values as $key=>$value){
echo $key."-".$value
}?>
Here is the link to Your request: <?php echo $data->linkToRequest;?>.
I would then save the parsed template, and instead of parsing the template every time, just pass the $data variable to the already parsed one, which would generate an output.
You simply generate the included file, you save it in a non-publicly accessible folder, and you include inside a PHP function using include($filename);
A code example:
function render( $___template, $___data_array = array() )
{
ob_start();
extract( $___data_array );
include ( $___template);
$output = ob_get_clean();
echo $output;
}
$data = array('Title' => 'My title', 'FirstName' => 'John');
render('templates/mytemplate.php', $data);
Note the key point is using extract ( http://php.net/extract ) to expand the array contents in real vars.
(inside the scope of the function $___data['FirstName'] becomes $FirstName)
UPDATE: this is, roughly, the method used by Wordpress, CodeIgniter and other frameworks to load their PHP based templates.
I'm not sure if understood your problem, but did you try using APC?
With APC you could cache variables so if you echo a specific variable, you could get it from cache.
You do all your calculations, save the information in some variables, and save those variables in the cache. Then, next time you just fetch that information from cache.
It's really easy to use APC. You just have to call apc_fetch($key) to fetch, and apc_store($key, $value, $howLongYouWant2Cache) to save it.
You best bet would to simply generate a PHP file and save it. I.e.,
$replacement = 'foobar';
$phpCodeTemplate = "<?php echo '$replacement'; ?>";
file_put_contents('some_unique_file_name.php', $phpCodeTemplate);
Just be very careful when dynamically generating PHP files, as you don't want to allow users to manipulate data to include anything malicious.
Then, in your process, simply check if the file exists, is so, run it, otherwise, generate the file.