PHP - Is there a way to "include" a string as a file? - php

There is a known way to include a file and capture its contents into a string while loading.
$string = get_include_contents('somefile.php');
function get_include_contents($filename) {
if (is_file($filename)) {
ob_start();
include $filename;
return ob_get_clean();
}
return false;
}
https://www.php.net/manual/en/function.include.php
Is there a way to "include" contents loading them from a string instead of a file?
I mean something like this:
$string = file_get_contents("file.php");
include_from_string($string);

If you want the string to be parsed as PHP code, just like the contents of a file loaded with include(), then the function you need is eval().
Note that, unlike code loaded by include(), code executed by eval() automatically starts in PHP mode, so you don't need to (and shouldn't!) prefix it with <?php. If you want to emulate the behavior of include() exactly, you can prefix the string to be eval()ed with ?> to leave PHP mode:
$string = file_get_contents( 'somefile.php' );
eval( '?>' . $string );
Also note that eval() is a very dangerous function to play with! While in this specific case it shouldn't be any more risky than include() itself is, using eval() on any string that might even possibly contain unsanitized (or insufficiently sanitized) user input is extremely dangerous, and may be exploited by attackers to execute malicious code on your system and thereby gain control of it.

This might not be what you are looking for but I got "work around" for it.
Just create temporary file with tempnam() which you will include and then unlink().
$path = "somefile.php";
$stringFile = file_get_contents($path);
$pathTmp = tempnam("tmp/", ""); // you pass directory in which you will store tmp files for me it's "tmp/"
$file = fopen($pathTmp, "w+");
fwrite($file,$widget);
fclose($file);
include $pathTmp; // include the file, and PHP will be automatically parsed
unlink($pathTmp); // delete file
THIS IS WRONG:
I'm not sure if it's good practice (but hack damn, it's simple) because no one suggested it but it's better then eval() which is basically "code hazard".
THIS IS RIGHT:
As #Chris Harrison commented this is security risk and it's equal to eval(). So you could basically do this:
eval($string);

This is a simple example for you, if you pass inside the eval() this will execute the code in the string variable.
<?php
//here your PHP Code goes
$string = get_include_contents('somefile.php');
//evaluating the string this will work
eval($string); //output

This is not equivalent to using include. Here's the problem: eval() takes the provided PHP, and executes it in the current environment. Thus, any globals, functions, classes, what-not, you have defined prior to the eval() are available for the processor. This is all good, and, upon return, the only thing left of the original (evel'd) string are the results of any echo (or equivalent) statements.
This is NOT the same as an include. There the file contents are merged with your source code and that is passed to eval(). Very, very different. The easiest way to see this is to define your string as 'class fu { static function bar() { echo "wow"; } ]' Put this in a file and call fu::bar() and you'll get 'wow' displayed. At the same point in your code, if you do an eval('class fu ...') and call fu::bar() from your code you'll get "Fatal error: Call to private method fu::bar() from context ..."
But, as long as you don't need to interact with the 'include' the results will appear the same.

Just echo whatever you want instead of include inside your function!
UPDATE
Your function should look like this:
$string = "Whatever";
$str = get_var($string);
function get_var($str) {
ob_start();
echo $str;
return ob_get_clean();
}

Related

Detect all PHP functions also with line break

I have a script with a regex, which detect all defined internal functions in php. The script is working well, but there is a problem with the linebreaks.
With this script I searching for internal and defined funtions from PHP. Every function have to be replaced with the new function "no_function()".
$functions=get_defined_functions();
for($i=0;$i<count($functions["internal"]);$i++){
//Include array functions
if($functions["internal"][$i]=="array"||$functions["internal"][$i]=="array_push"){
}else{
$code=preg_replace('#('.$functions["internal"][$i].'[ |\n|\r|\t]*\([ |\n|\r|\t]*.*\))#i',"no_function()",$code);
}
}
When I had a function like:
str_replace($search,$replace,$string);
The function will not called because it will replace with no_function();
It will work normally. But if I have a function like that:
str_replace($search,
$replace,
$string);
The regex don't detect that, but PHP will execute that as well. I am a noob with regex. Can someone help me?
Thanks for every response.
Not sure about your use case. But you could use namespaces and redeclare internal functions under your namespace for a quick hack that will replace internal functions with no return.
First make a file consisting of dummy internal functions.
<?php
$funcs = get_defined_functions();
$output = "<?php\n";
$output .= "namespace example;";
foreach ($funcs['internal'] as $func_name) {
$output.= "function $func_name () {}\n";
}
file_put_contents('dummy_funcs.php', $output);
Then in another file (perhaps a common bootstrap) include your dummy functions early.
<?php
namespace example;
include 'dummy_funcs.php';
echo str_replace('w', 'l', 'bawls');
Outputs nothing.
The upshot here is that you don't need to edit your code (other than adding the include). It could however be a pain depending on your existing namespacing.

PHP code from a file does not execute

I am working on a BB code system for a content manager and I want to be able to use something like [code=php]<?php echo "Hello World!"; ?>[/code] in my textarea. Using GeSHi (A syntax highlighter) I have made the following function to parse the code:
function parsecode($codetype) {
$source = file_get_contents("file.php");
$language = $codetype;
$geshi = new GeSHi($source, $language);
echo '<code class="num">', implode(range(1,count(file("file.php"))), "<br />"), "</code>";
echo $geshi->parse_code();
}
This works perfectly fine!
Now this is where the BB code comes in. Using preg_replace I made a simple system that finds and replaces bits of code:
$find = array(
"/\[code\=(.+?)\](.+?)\[\/code\]/is"
);
$replace = array(
'<?php parsecode("$1"); ?>'
);
Yes, for now this means it only reads the language and parses the file "file.php" but eventually I will have this work different, but that's not important for now.
What happens, is that the BB code gets executed correctly, and the result is that it does in fact execute the code, but it does NOT execute the function parsecode() . I made a small adjustment to find out where the problem is, and made it save to a file and it turns out the file contained the following: <?php parsecode("php"); ?> . Which is exactly what it should contain. When I write this line of code in the file, it executes.
Anything submitted in the textarea gets stored in a file, which is then read using fopen() and then echo'd on a different page.
My question: Why does the function not execute & parse the code like it should?
Thanks ahead!
There is only one way to get PHP code to execute within PHP code (change code dynamically) and that is with eval().
http://www.php.net/manual/en/function.eval.php
This let's you dynamically make code and execute it
Please remember this quote though:
"If eval() is the answer, you're almost certainly asking the wrong question. -- Rasmus Lerdorf, BDFL of PHP"
eval() is known for security vulnerabilities and being exploited. Highly not recommended.
However, as long as you're not using user generated code IN the eval you will be fine. You could put a return around it to get the result only in the database.
You could instead achieve the same effect by running this in the script but not replacing it before it's run in the entry but on the forum page itself...

Php: avoiding function being treated as string

I want to treat the contents of a website as a string, and assign to a variable.
However, if I write <?php $stringvariable = ' include https://api.twitter.com/1/statuses/user_timeline/USER.rss ' ?>
php will assume that the include function, and the address contained within, are merely a string.
Is there some way to avoid this?
P.S. I'll probably be actually using the function read_file as a basic security measure in the really unlikely event that the RSS feed from which I'm reading gets hacked.
$variable = file_get_contents(URL)
Try this
$stringvariable = file_get_contents('https://api.twitter.com/1/statuses/user_timeline/USER.rss');
DO NOT USE INCLUDE FOR THIS PURPOSE!
PLEASE NOTE
Include is NOT a function - it is control structure!
http://php.net/manual/en/function.include.php

How to execute text as PHP

I have a problem, I want to grab text and execute text as PHP, but how do I do this? For example I have this code in a .txt file:
$tweetcpitems->post('statuses/update', array('status' => wordFilter("The item Blue has been released on Club Penguin.")));
$tweetcpitems->post('statuses/update', array('status' => wordFilter("The item Green has been released on Club Penguin.")));
Now the problem is that I grabbed this text and I want to execute it as a PHP script, how do I do this? Please help!
eval(file_get_contents('yourfile.txt'));
BE CAREFUL!
http://php.net/manual/en/function.file-get-contents.php
http://php.net/manual/en/function.eval.php
You can run both text and eval from the same script but like previously mentioned. Security must be really tight. Nevertheless, the eval funtion is really powerful if you use it properly. Try the code below.
$b = 123;
$a = "hello <?php echo 'meeeee'; ?>. I just passed $b from the mother script. Now I will pass a value back to the mother script" . '<?php $c; $c = 1 + 8; ?>' .
"I was call within a function, therefore my variable can't passed to the global script. Nonetheless, let try something globally" .
"<?php
global \$d;
\$d = 'I am now a global var. Take care though, don\\'t let anyone edit your file' ;
";
function parseTxtAsCode($invalue){
if( !is_string($invalue) ) return false;
eval('?>' . $invalue);
echo "\n\n\n\n Can't believe I got this from my child: $c \n";
}
parseTxtAsCode($a);
echo "\n\n\n I am global and this is what I got from the eval function: $d";
You can evaluate text as PHP using eval; however, read below for a very important disclaimer!
The eval() language construct is very dangerous because it allows execution of arbitrary PHP code. Its use thus is discouraged. If you have carefully verified that there is no other option than to use this construct, pay special attention not to pass any user provided data into it without properly validating it beforehand.
// $result is a string containing PHP code. Be sure you trust the source of
// the PHP code prior to running it!
eval( $result );
You can use the include() or the require() funcions :
include(/your_text_file.txt);
// OR
require(/your_text_file.txt);
Or the Eval function (like the 1st comment)

PHP assign variable definition from a string

Let's say I have a file "English.txt" containing these lines :
$_LANG["accountinfo"] = "Account Information";
$_LANG["accountstats"] = "Account Statistics";
Note : the file extension is .txt and there is nothing I can do to change that. There is no opening PHP tag (<?php) or anything, just those lines, period.
I need to extract and actually get the $_LANG array declared from these lines. How do I do that? Simply includeing the file echoes every line, so I do
ob_start();
include '/path/to/English.txt';
$str = ob_get_clean();
Now, if I call eval on that string, I get an syntax error, unexpected $end. Any ideas?
Thanks.
eval(file_get_contents('English.txt'));
however, be sure NOBODY can change English.txt, it could be dangerous!
First of all, note that you should use file_get_contents instead of include with output buffering. Since it contains no <?php tag, there is no need to run it through the script processor.
The following works perfectly in my tests:
<?php
$contents = file_get_contents("English.txt");
eval($contents);
var_dump($_LANG);
As one of the comments said, if you do the above and still get an error, then your file does NOT contain exactly/only those lines. Make sure the file is actually syntax compliant.
As has been mentioned, you should really use eval only as a last resort, and only if the file is as safe to execute as any code you write. In other words, it must not be editable by the outside world.

Categories