how to eval() a segment of a string - php

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.

Related

How to echo usable php code from database

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.

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 quoted_printable_decode get html part

I am not able to figure out how to get an HTML out of a simple quoted_pritable_decode command.
Consider the following code from w3schools.
$str = "Hello=0Aworld.";
echo quoted_printable_decode($str);
The output for this code is:
Hello world.
However, when I view the source it is:
Hello
world.
Well, I am trying to figure out if there is a simpler way to get the second output. I would like to store it in my database in HTML format. I am aware of way arounds like replacing the encoded part, however, is there a recommended way here?
Edit 1:
Both the answers are perfectly fine and a precise explanation from Xavier was great. Since, I just have to mark one as correct, I mark the one which I believe is more precise.
You could use nl2br() encapsulating that when you are storing it into your table.
<?php
$str = "Hello=0Aworld.";
echo nl2br(quoted_printable_decode($str));
Change your code to:
$str = "Hello=0Aworld.";
echo "<pre>" . quoted_printable_decode($str) . "</pre>";
What you echo is being interpreted as pure HTML, and HTML doesn't honor newlines, except when you use tag. You also could do a echo str_replace('\n','<br>',quoted_printable_decode($str)); (i.e. AFTER decoding)

PHP echo-ing a PHP code inside an echo

I'm quite new here. I'm trying to make a blog/journal site that allows users to post their own journal. I'm still quite reluctant on making it because I am really afraid of malicious code injections.
So here's a sample code:
<?php
$test = "<b>blah</b>"; //User input from SQL
echo "$test";
?>
What will come out is just the word "blah" in bold right? What I was trying to achieve was to echo "<b>blah</b>" instead. I don't want people to put some PHP codes that can actually mess up my whole web page. Please keep in mind that the variable $test is actually a MYSQL query, so that variable will be needed as an example. I know you can do echo '$test'; but it just comes out as "$test" instead. I feel like pulling my hair out I can't figure it out yet.
The second solution I know of is the htmlspecialchars(); function, but I want the strings to display as what I typed, not the converted ones...
Is there any way I can do that?
I think the OP wants the HTML itself to be output to the page, and not have the tags stripped. To achieve this, you can run the string first through htmlentities()
$test = '<b>blah</b>';
echo htmlentities($test);
This will output:
<b>blah</b>
Which will render in the page as
<b>blah</b>
Echo don't execute PHP code from string. This is impossible and this is not security hole in your code.
You can use a template engine like Twig for exemple.
If htmlspecialchars(); is not the one you are looking for, try the header() option.
header('Content-type: text/plain');
When you are gonna give <b>Hi</b> to a browser, it will be displayed in Bold and not the text be returned. But you can try this way, outputting it inside a <textarea></textarea>.
Or the other way is to use htmlentities():
<?php
$test = "<b>blah</b>"; //User input from SQL
echo htmlentities("$test");
?>

Is there a php function for using the source code of another web page?

I want to create a PHP script that grabs the content of a website. So let's say it grabs all the source code for that website and I say which lines of code I need.
Is there a function in PHP that allows you too do this or is it impossible?
Disclaimer: I'm not going to use this for any illegal purposes at all and not asking you too write any code, just tell me if its possible and if you can how I'd go about doing it. Also I'm just asking in general, not for any specific reason. Thanks! :)
file('http://the.url.com') returns an array of lines from a url.
so for the 24th line do this:
$lines = file('http://www.whatever.com');
echo $lines[23];
This sounds like a horrible idea, but here we go:
Use file_get_contents() to get the file. You cannot get the source if the web server first processes it, so you may need to use an extension like .txt. Unless you password protect the file, obviously anybody can get it.
Use explode() with the \n delimiter to split the source code into lines.
Use array_slice() to get the lines you need.
eval() the code.
Note: if you just want the HTML output, then ignore the bit about the source in step 1 and obviously you can skip the whole eval() thing.

Categories