65

I want to require/include a file and retrieve its contents into a variable.

test.php

<?php
echo "seconds passed since 01-01-1970 00:00 GMT is ".time();
?>

index.php

<?php
$test=require("test.php");
echo "the content of test.php is:<hr>".$test;
?>

Like file_get_contents() but than it should still execute the PHP code. Is this possible?

alex
  • 479,566
  • 201
  • 878
  • 984
user746379
  • 1,492
  • 2
  • 13
  • 21
  • 1
    It might be, but I think you might want to ask yourself (or us, if needed) why you would need this, and if there isn't another way. You could do all sorts of things (like executing it using exec or `php yourfile.php` and then retrieving the results), but there might be better ways to actually fix your initial problem... – Nanne May 10 '11 at 10:04
  • it just happends to be handy in my situation. There will likely be a better way but I've got yet to learn it. For now even just knowing about the possibility is enough since it does expand my knowledge. – user746379 May 10 '11 at 10:08
  • 1
    @user746379, In your included file, just simply do `return 'value';`. It will work. – Pacerier Aug 07 '13 at 11:43

9 Answers9

98

If your included file returned a variable...

include.php

<?php
return 'abc';

...then you can assign it to a variable like so...

$abc = include 'include.php';

Otherwise, use output buffering.

ob_start();
include 'include.php';
$buffer = ob_get_clean();
Community
  • 1
  • 1
alex
  • 479,566
  • 201
  • 878
  • 984
88

I've also had this issue once, try something like

<?php
function requireToVar($file){
    ob_start();
    require($file);
    return ob_get_clean();
}
$test=requireToVar($test);
?>
Jesse Rusak
  • 56,530
  • 12
  • 101
  • 102
user6
  • 1,999
  • 2
  • 23
  • 29
  • 14
    Wrong! `ob_start()` enables turns on output buffering, `ob_clean()` - just cleans the buffer and leaves output buffering turned on, which is wrong! To turn it off, use `ob_end_clean()` instead of `ob_clean()`. Alternatively, you can use `ob_get_clean()` instead of both `ob_get_contents()` and `ob_end_clean()`. So the body of a function would look like `ob_start(); require $file; return ob_get_clean();`. – binaryLV May 10 '11 at 10:15
  • 6
    Also good to know: ob_start is stackable, so this method is perfectly safe to use within code that was already inside an buffered output block. – Mahn Jun 24 '12 at 23:41
  • 2
    Also `require` isn't a function so the parenthesis there are redundant. – alex Jan 20 '16 at 10:14
  • But what if i am trying to still access a variable? Lets say test.php would have super complex algorithms that require a lot of calculations. I need the content of this file in my var like shown, but also want to access the variables, that are created within my test.php. That means, that first I have to execute your `requireToVar($ifle)` and then also include the file like normal, which results in doubled execution of my code. – Seba M Nov 15 '19 at 12:17
8

You can write in the included file:

<?php
    return 'seconds etc.';

And in the file from which you are including:

<?php
    $text = include('file.php'); // just assigns value returned in file
Tadeck
  • 132,510
  • 28
  • 152
  • 198
  • 3
    This is the best solution for several types of requirements to include a file into a variable. – Cameron Apr 23 '14 at 00:00
  • Great solution, it's useful for caching file, so I can use the included files several times without to include again the files, I need only print out the variable content! I use always this approach! Thanks! – Alessandro Nov 02 '20 at 12:00
1

In PHP/7 you can use a self-invoking anonymous function to accomplish simple encapsulation and prevent global scope from polluting with random global variables:

return (function () {
    // Local variables (not exported)
    $current_time = time();
    $reference_time = '01-01-1970 00:00';

    return "seconds passed since $reference_time GMT is $current_time";
})();

An alternative syntax for PHP/5.3+ would be:

return call_user_func(function(){
    // Local variables (not exported)
    $current_time = time();
    $reference_time = '01-01-1970 00:00';

    return "seconds passed since $reference_time GMT is $current_time";
});

You can then choose the variable name as usual:

$banner = require 'test.php';
Álvaro González
  • 142,137
  • 41
  • 261
  • 360
  • Works in PHP5 too. Not sure if it's required, but I use brackets in the syntax `$banner = (require 'test.php');` – Slava Jan 18 '17 at 15:27
  • @Alph.Dev I believe [it doesn't](https://3v4l.org/K716N). [Anonymous functions](http://php.net/manual/en/functions.anonymous.php) are fairly old but the self-invoke syntax (I can never remember the actual name) is newer. However, the syntax for older systems is neat too so I've updated the answer. – Álvaro González Jan 18 '17 at 16:00
  • Yes. `call_user_func(function(` makes it work in PHP5 indeed. Unfortunately I can't remember why, but we intentionally use brackets around `(require 'file.php');` It caused some problems without them. – Slava Jan 18 '17 at 16:17
  • @Alph.Dev [include](http://php.net/manual/en/function.include.php) documentation just says: "Because include is a special language construct, parentheses are not needed around its argument. Take care when comparing return value." – Álvaro González Jan 18 '17 at 16:25
0

It is possible only if required or included php file returns something (array, object, string, int, variable, etc.)

$var = require '/dir/file.php';

But if it isn't php file and you would like to eval contents of this file, you can:

<?php

function get_file($path){

    return eval(trim(str_replace(array('<?php', '?>'), '', file_get_contents($path))));
}

$var = get_file('/dir/file.php');
dr.dimitru
  • 2,645
  • 1
  • 27
  • 36
0

Or maybe something like this

in file include.php:

<?php
  //include.php file
  $return .= "value1 ";
  $return .= time();

in some other php file (doen't matter what is a content of this file):

<?php
  // other.php file
  function() {
    $return = "Values are: ";
    include "path_to_file/include.php";

    return $return;
  }

return will be look like this for example:

Values are: value1, 145635165

The point is, that the content of included file has the same scope as a content of function in example i have provided about.

tomslou
  • 51
  • 2
0

Use shell_exec("php test.php"). It returns the output of the execution.

kapa
  • 77,694
  • 21
  • 158
  • 175
ankitjaininfo
  • 11,961
  • 7
  • 52
  • 75
0

require/include does not return the contents of the file. You'll have to make separate calls to achieve what you're trying to do.

EDIT

Using echo will not let you do what you want. But returning the contents of the file will get the job done as stated in the manual - http://www.php.net/manual/en/function.include.php

JohnP
  • 49,507
  • 13
  • 108
  • 140
0

I think eval(file_get_contents('include.php')) help you. Remember that other way to execute like shell_exec could be disabled on your hosting.