TempAccount12345
TempAccount12345

Reputation: 41

Include -- using a string rather than a filename

I'd like to run include on a string rather than a file, but an unaware of how to achieve this.

//This is the desired functionality
include($filename);

//But I want to do something like this instead.
$file_contents = getFileFromCacheOrSomewhereElse($filename);
include($file_contents);  // Doens't work...
eval($file_contents);     // Also incorrect.

Please note: "eval" is not the same as include -- "include" echos out the contents of the file (and executes any PHP tags) while "eval" executes the string as PHP code.

An example use case is loading a template file from Memcache (as a string), then running include on that string, rather than running include and relying on PHP filecache.

Upvotes: 3

Views: 4352

Answers (3)

Your Common Sense
Your Common Sense

Reputation: 157989

Storing PHP code in the memcache is not the best idea.
And evaling it thereafter is even worse.

Any opcode cache, APC or EAccelerator will cache your PHP files on the fly, with no strange efforts like this, and even parse it for the faster execution.

EDIT. Given the voting results after all these years, I assume that this question is attracting only noobs, who have the same strange whim. So I have to repeat: although it defeats your brilliant idea,

just leave your includes as is

They will be cached much better and executed much faster by the internal PHP's opcode cache.

Upvotes: 1

salathe
salathe

Reputation: 51970

If you can turn on the allow_url_fopen and allow_url_include php.ini settings, then an alternative is the data stream wrapper (manual).

include 'data:text/plain,' . urlencode($file_contents);

Upvotes: 10

Moritz Both
Moritz Both

Reputation: 1628

eval("?>" . $file_contents . "<?php ");

does it.

Upvotes: 7

Related Questions