Inline PHP (command line) - php

I would like to make something like tryruby.org. I take a line from the user (e.g., echo __FILE__) and I want to execute it in PHP and return the output back to the client.
I tried to do exec('php -r ' . $command, $output), but $output always contains the PHP help section.
How can I implement this feature?

To make php -r you have to have to put the code you want to execute between ' .. your code .. '
Example:
php -r ' $var = 34; print_r($var); '

It looks like your problem is that you aren't wrapping your code to be executed with ' '. You also need to be wary of ' in the code, special characters, escape sequences, etc.
In fact, if you insist on using exec(), it might be better to do this (to completely avoid having to worry about escaping and the such):
$command = base64_encode($command);
exec("php -r 'eval(base64_decode(\"$command\"));'", $output);
You could use eval() instead of what you're posting above.
The main issue here (both with eval() and your exec() code) is that taking PHP code from user input simply isn't safe:
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.
Suggestion
Since you want to return the result of the PHP code, you could potentially do something cool with Ajax, where you pass the PHP code to a script (Base64 encoded, perhaps) as a parameter:
$code = base64_decode($_GET['code']);
// Clean the user input here
eval($code);
Ajax example using jQuery:
// assuming `code` contains the PHP code
var encoded = base64_enc(code);
$.get('execute.php?code=' + encoded, function(data) {
var result = new String(data);
// do something with the result here, such as displaying it
}, dataType='text');
For Base64 encoding in JavaScript, see this.

http://tryruby.org seems have an interactive Ruby shell. That seems to be a good starting point.
Here are two projects that provide such a shell for PHP: php_repl and phpsh.
The other part is the web interface for the interactive shell. For that part, I suggest you have a look at repl.it, which provides this service for many languages (but sadly not PHP). Here's a link to it's source code.
With this combination, you should be able to complete cour project.

Look up 'eval()' and more importantly, why eval() and what you're trying to do is very difficult to achieve in a secure manner. Imaging for example the user who inputs:
echo file_get_contents('/etc/passwd');
You'll need quite a bit of work to make this secure, including watching and filtering all system calls being made from the eval'd process.
Cheers

Related

How to run file in background by adding variable

Hey PHP developers I am newbie.
Today I want to run my process.php file in the background because it takes too much time to load... Here is the code that I want to use.
$proc=new BackgroundProcess();
$proc->setCmd('exec php <BASE_PATH>/process.php hello world');
$proc->start();
And I want to add this ids=$postid&reaction=$reaction variable instead of hello world.
And want to receive it with post in process.php file like this
$id =$_POST['ids'];
$type = $_POST['reaction'];
I am using this GitHub file
https://github.com/pandasanjay/php-script-background-processer/blob/master/README.md
Before doing downvote answer me I am a newbie in PHP.
You can try exec() for this. If you want to pass parameters then try like this.
//it will store logs to log_data.log
exec("php process.php $id $type >log_data.log &");
Hope this will work for you :)
Try like this
function execInBackground() {
//this will run in background
exec("php process.php $id $type > /dev/null &");
}
As soon as it is not HTTP request at all, you cannot access $_GET and $_POST superglobals. The right way to receive arguments in this case, is to access the array $argv. See official documentation:
http://php.net/manual/en/reserved.variables.argv.php
UPD: And, well, if you really want to pass $_GET/$_POST params to this script executed via shell, here is a dirty trick:
$get_params_as_string = base64_encode(json_encode($_GET));
$proc=new BackgroundProcess();
$proc->setCmd("exec php <BASE_PATH>/process.php {$get_params_as_string}");
$proc->start();
And in your process.php access it like this:
$get_params = json_decode(base64_decode($argv[1]), true);
So, we are just created JSON from $_GET array. Then, as we know that JSON string contains special characters(like ", {, }, etc), and to avoid dealing with problems of escaping and unescaping, we simply encode this string as base64. It guarantees us absence of special characters in result string. Now we can use this string as a single argument, which we will pass to shell command (your BackgroundProcess). And finally, in process.php we can access this string from $args[1], then decode from base64, then decode from JSON to a regular PHP array. Here we go.
This solution is provided only for educational purpose, please don't ever do it in real life.

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...

Is it possible to execute code using a URL?

Is it possible for someone to execute a code through a URL for example
http://localhost/page.php?code=echo 'something';
If yes then how can it be done and how can you prevent it from happening?
It's possible if something on the server takes the data in the URL and puts it somewhere where it might be treated as code (e.g. in an eval statement, in an SQL query or in an HTML document).
The defences are all specific to the place where you put the data, but usually involve escaping it.
See also SQL Injection, XSS, and the open web application security project.
After looking around for a while, I found eval which is a function that is capable of executing any php code provided in a GET like my example above, I used the following code to test it.
<?php
$code = $_REQUEST['code'];
eval($code);
?>

PHP eval issue with PHP + HTML code

I've got PHP and HTML code stored in a database table. When I get this data, I need to echo the HTML and process the PHP. I thought I could use eval() for this, which works, if I do this eval("echo 'dlsj'; ?> EVALED "); I get "dlsjEVALED" printed out.
The problem is, I get a fatal error when I run longer scripts. Things like:
Parse error: syntax error, unexpected '<' in /home/content.php(18) : eval()'d code on line 1
Best advice - never store php and html code in your database. And avoid eval() like the plague.
I can't really tell what's wrong with your code, as you haven't provided enough information. But even if I did have some advice, I don't think I could give it in good conscience.
You should redesign your whole application so that it doesn't require storing such things in the database. I can't imagine why it would be necessary.
just right der...........
eval('?>' . $content .'<?php');
You need to re-open php mode after the EVALED. Apparently you have to do this with <? rather than the full <?php.
As a rule eval is to be avoided. But rules are made to be broken. There's a thread at When is eval evil in php? that gives some less dogmatic advice.
Depending on what you want to do, it might be suitable to use a template file that you source, with text that will vary stored in a local variable prior to sourcing the template.
As for storing code to be executed in the DB... this does happen in some frameworks like Drupal to provide convenient extensibility, but then Drupal is pretty thoroughly scoured for security weaknesses.
Also if you're writing self-modifying code then you need to use eval(). Not sure if anyone has done that in php but it would certainly be interesting.
I would guess that you're trying to eval() something that contains an opening <?php tag. And that leads to the error at hand.
$contents = htmlentities($contents);
echo html_entity_decode(eval($contents));

how to eval() a segment of a string

I have a string that has HTML & PHP in it, when I pull the string from the database, it is echo'd to screen, but the PHP code doesn't display. The string looks like this:
$string = 'Hello <?php echo 'World';?>';
echo $string;
Output
Hello
Source Code
Hello <?php echo 'World';?>
When I look in the source code, I can see the php line there. So what I need to do is eval() just the php segment that is in the string.
One thing to consider is that the PHP could be located anywhere in the string at any given time.
* Just to clarify, my PHP config is correct, this is a case of some PHP being dumped from the database and not rendering, because I am echo'ing a variable with the PHP code in it, it fails to run. *
Thanks again for any help I may receive.
$str = "Hello
<?php echo 'World';?>";
$matches = array();
preg_match('/<\?php (.+) \?>/x', $str, $matches);
eval($matches[1]);
This will work, but like others have and will suggest, this is a terrible idea. Your application architecture should never revolve around storing code in the database.
Most simply, if you have pages that always need to display strings, store those strings in the database, not code to produce them. Real world data is more complicated than this, but must always be properly modelled in the database.
Edit: Would need adapting with preg_replace_callback to remove the source/interpolate correctly.
You shouldn't eval the php code, just run it. It's need to be php interpreter installed, and apache+php properly configured. Then this .php file should output Hello World.
Answer to the edit:
Use preg_replace_callback to get the php part, eval it, replace the input to the output, then echo it.
But. If you should eval things come from database, i'm almost sure, it's a design error.
eval() should work fine, as long as the code is proper PHP and ends with a semicolon. How about you strip off the php tag first, then eval it.
The following example was tested and works:
<?php
$db_result = "<?php echo 'World';?>";
$stripped_code = str_replace('?>', '', str_replace('<?php', '', $db_result));
eval($stripped_code);
?>
Just make sure that whatever you retrieve from the db has been properly sanitized first, since you're essentially allowing anyone who can get content into the db, to execute code.

Categories