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)
Related
I have a settings page in my Wordpress Admin Panel where I save some HTML code(with some PHP code in it) as a Wordpress Option, using update_option.
In phpmyadmin, the value is stored exactly like this:
<img src = \"<?php bloginfo(\'template_directory\'); ?>/images/flexslider/phone.png\">
It works perfect until I try to actually make the code work in a page. I'm printing it like this:
<?php echo urldecode(get_option('wp_slider_code')); ?>
This, unfortunately, prints the PHP code as it was HTML code. So the PHP code doesn't actually get executed; it's treated like a text, the url becoming:
<?php bloginfo('template_directory'); ?>/images/flexslider/phone.png
What can I do to make this PHP code get executed when I echo it on a page?
You have to use the eval() built-in function:
eval( $YourString );
(Edit:) If $YourString return a result, to cath the result you have to use:
$result = eval( $YourString );
Please note:
Caution
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.
Read mor on PHP Documentation.
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...
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();
}
I need to echo a var in a page but the value is declared later after being included in the page.
Is there any way to echo a var before I declare it? or some way to include the page withought running any of the code and just getting the var?
No language is obviously able to output a value, before it exists.
If you want to do something like..
echo $var;
$var = "Hello world";
Then the answer is no. PHP is an interpreted language which runs downwards, not every which way.
The simplest, best and most sensible option is to fix your logic so everything happens in a logical order.
Failing that. Store your data in a variable instead of outputting it. Include a placeholder where you want the variable to be. Then do a search and replace on that placeholder once you have the data you need.
You can build a template-like solution. Put something like ##var## in the page, use ob_start() at the beginning of the page, define your $var whereever, then, at the end of the page, use echo str_replace('##var##', $var, ob_get_clean());.
Example:
<?php ob_start() ?>
<p>##test##</p>
<?php $test = "this is a test paragraph" ?>
<?php echo str_replace("##test##", $test, ob_get_clean()) ?>
Check out ob_start(), and ob_get_clean().
There is a way to use JavaScript with PHP for this kind of echos.
$echo = document.getElementById('dispaly_div').innerHTML = "$variable";
One way is to use functions.
For example:
function printvar($string) {
echo $string;
}
printvar("Hello World!");
This is tested and works.
I have a load of php templates which uses a custom translate function "__", i.e.
<?php echo __("Hello"); ?>
I need to write a script which will look for all these function calls (there are about 200 templates).
I.e. it will find __("Hello") and add it to a sentences to be translated array. For example it will find:
$sentences[] = "Hello";
$sentences[] = "Goodbye";
$sentences[] = "Random sentence to be translated";
Basically i need to find the strings which need to be translated.
Which do you think is the best language for doing the script in? and do you think it will be best to use a regular expression?
Any help to point me in the right direction would be superb!
Thanks
I always jump to Perl for string manipulation problems.
However, awk or sed could easily solve your problem.
For example, in Perl:
while(<>) {
if( $_ =~ /echo __\((".*?")\)/ ) {
print '$sentences[] = ' + $1;
}
}
Note, this will only capture one string per line. You can do more, but I'll leave that as an exercise to the reader.
Also, the 'while(<>)' will loop through each line in each file you pass on the command line. There's also a way read all of the files in a directory if that's what you need.