Say I have a variable of a string that contains an html page. Within that html page variable I have an echo statement-
e.g. <?php echo 'whatever' ?>
Can I somehow "render" that variable to the browser, and have php evaluate all the php statements within the variable?
If I just echo the variable, the html renders fine but the php statements are not evaluated.
If I try running eval on the entire page, it just throws an exception (makes sense).
I know this all sounds like bad practice, but I'm trying to figure out a way to do this without saving the variable to a file and loading the file.
BTW: I'm doing this all within codeigniter, so if there's a way to use $this->load->view on that variable... that would be even better :)
Example Code:
$x = /* Some logic to get a template data from another server */
/* $x is "<html><?php echo 'bla'; ?></html> */
echo $x;
This doesn't work- trying to run echo eval($x) also doesn't work
You can write view data to variable and use this variable in other view
In you controller:
$data['view1'] = $this->load->view('my_view1', '', TRUE); // write view data to variable
$this->load->view('my_view2', $data);
In my_view2:
<html>
<?=$view1?>
</html>
This docs can help you Returning views as data - Codeigniter
I'm not sure I follow you, but I think this is what you want.
If page1_view.php contains HTML and needs to echo a variable. e.g.
<div>Foo says: <?php echo $whatever; ?>!!!</div>
To get that "view" as a string with the variable $whatever evaluated you need this.
$view_data['whatever'] = "Hello World";
$page1 = $this->load->view('page1_view', $view_data, TRUE);
$page1 now contains a string which is the contents of page1_view.php. in this case
"<div>Foo says: Hello World!!!</div>"
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
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.
Is it bad practice to echo out a bunch of HTML using a function in php and having it something like this:
function my_function() {
global $post;
$custom_fields = get_post_custom();
$some_field = $custom_fields ['some_field'][0];
?>
<div class="something <?php if ($some_field) { echo $special-clas;} ?>">
<div class="something-else">
/* bunch more of html code */
</div>
</div>
}
And then in the page where you want to use that to echo it?
<html>
<body>
.....
....
<?php echo my_function(); ?>
....
I'm unsure how "accepted" it is to echo out functions?
Consider two functions:
function does_return() {
return 'foo';
}
function does_echo() {
echo 'bar';
}
does_return(); // nothing displayed
echo does_return(); // 'foo' displayed
does_echo(); // 'bar' displayed
echo does_echo(); // 'bar' displayed
In both cases, output CAN be performed, but how it happens differs. Since does_return() does not itself have ANY code to perform output within its definition, output is up to the calling code, e.g. the echo you perform.
With does_echo(), it doesn't matter how you call the function (with or without echo), since the function does the output itself. you'll get bar regardless.
Now consider this:
function this_is_fun();
echo 'foo';
return 'bar';
}
this_is_fun(); // outputs 'foo'
echo this_is_fun(); // outputs 'foobar';
This is bad practice, because it makes your code hard to maintain.
With a function like that you are mixing the logic and presentation. So, when you see something in your output that you don't like you can not be sure where to go first to go and change it. Do you go to the page code or the function code?
Functions are supposed to return data, and then your application deals with it how you wish, whether that’s assigning it to a variable or echoing it out.
I don't see how it's bad practice. As long as you're reusing the function, then it seems like you're using it the right way.
The only thing you shouldn't be doing is using global; rather pass $post to the function. See this answer for why.
Since your function already has an output, you don't need the echo.
my_function( $post );
That's fine. I'd rather see that than the PHP mixed in completely to the HTML.
You can use <?= my_function() ?> instead if you want to write a little less code.
What #DaveRandom said in his comment. Aside from that, no, it's not necessarily bad practice. It can though make for code that's hard to debug. Consider a MVC approach instead where the logic is largely in the Controller and the View simply handles rendering the view based on that logic.
Not sure if this is possible but what I am wanting to do is echo a html text link only if the page contains certain php code, in particular just the opening reference of 'myApi'. So if the page contains the following code:
<?php myAPI(variables); ?>
Then I would like to include this somewhere else on the page
<?php echo 'Click Here'; ?>
Any help would be much appreciated, thanks :)
Set an if somewhere, and use isset to test if your API has set a specific variable or not.
if(isset($apiVariable)) {
echo "link content...";
}
(The variable should be specific to your API, obviously.)
Update
I said "somewhere", but it's probably best to do the test logic it in a separate place than where you output the HTML. In that case, you'd need a flag for when you're ready to spit out the HTML:
isset($apiVariable) ? $apiFlag = true : $apiFlag = false;
// continue other PHP operations...
//...now your logic is finished, output HTML.
if($apiFlag) { echo "<a>Link</a>"; }
That way, when you re-visit the page later for revision or update, your logic not all mixed up with your display.
<?php if (isset($variable)): ?>
Click Here
<?php endif; ?>
The function isset() check if the variable is set and returns a boolean. so you can use it to check if a variable exist.