ob_start() not replacing content - php

<?php
ob_start(function($buffer){
$buffer = preg_replace("/{%(data_.*?)%}/", '<?php echo $data[\'slot_$1\']; ?>', $buffer);
$buffer = preg_replace("/{%menu_(.*?)%}/", '<?php echo insertNav($_data[\'slot_$1\']); ?>', $buffer);
return $buffer;
});
?>
Trying to use the preview code to replace content with php code. Basically, it is for an editor similar to this one on stack overflow where if you type ** strong text ** = strong text except I'm using it to pull data from a database for a particular item. I am using {%data_#%} to get the # and replace it with $data['slot_#'] just for a reference on what I am doing with this.
If I replace <?php echo $data[\'slot_$1\']; ?> with 'Hello' it echoes out Hello. So why isn't it echoing out the php code?
EDIT
I replaced it with $buffer = preg_replace("/{%(data_.*?)%}/", '$1', $buffer); and it echoes out data_1. It isn't getting the # value and placing it into the php code echoed out. The echoed out code appears to be $data['slot_data_#] instead of $data['slot_#']. It is only supposed to get the number when typing in {%data_#%}
EDIT 2
I finally got the number to echo out. Turns out I had a ( in the wrong spot. Here is my new line: $buffer = preg_replace("/{%data_(.*?)%}/", '<?php echo $data[\'slot_$1\']; ?>', $buffer);.... however, it still is leaving everyhting blank. I know that $1 is now echoing out the correct number, but when I put it into the php code, nothing gets echoed out on the page. And I copied and pasted that php code directly in and replaced the number with $1 so that should be right.

<?php
ob_start(function($buffer){
$buffer = preg_replace("/{%data_(.*?)%}/", '?><?php echo $data["slot_$1"]; ?><?php', $buffer);
$buffer = preg_replace("/{%menu_(.*?)%}/", '?><?php echo insertNav($_data["slot_$1"]);?><?php', $buffer);
return eval($buffer);
});
PHP codes within ob_start are not executed in this way, you should work with an evil function: eval()

Over the past few days, I found that using ob_start() to return php code can only be done via eval() and that it is somewhat of an unsafe code as it leaves you open to php injections. Thank you #revo
I have transitioned over and learned how to code a template engine and used a .tpl file so that users cannot put their own php code into the page and everything gets processed using a php page running in the background using functions (template engine). This prevented me from having to use an eval() code as #revo recommended that I stick away from using this without proper validation (which I'm not sure I want to even have to worry about the validation to be honest).
I wanted to inform everyone who viewed this question of what I learned and would suggest working with template engines & functions and avoid using the method I am recommending in my question.
Thank you #revo for working with me on a possible solution and keeping me informed of vulnerabilities.

Related

PHP output buffer corrupted getting include contents

Stranger things... hard to make this "question". I have an entire website made in php and JavaScrip. The contents are processed in many ways, accessing mySQL and files. One way is just to include a php that build the html string. To include right in the structure of the website, I did a simple output buffer:
ob_start();
include_once($url);
$output = ob_get_contents();
ob_end_clean();
echo_cont($output);
Where echo_cont simply store the contents to print later, on the right place. But a "simple" page that read some photo files and build an album is coming corrupted. Parts of html missing, strange changes like this:
class=" button2" when should be class="button2" so the element become
unformatted
"http www.mywebsite.com.br folder" when it suppose to be
"http//www.mywebsite.com.br/folder"...
Other pages are being included right.
I began to use output buffer in this site this year, I don't know if can be a problem of this kind or might be something else, but is not easy to look for clues, is not easy to run the page outside the site because it depends on several libraries - is kinda complex. It seams to me a text encoded and bad decoded later. What do you think?
EDIT: the echo_cont function:
$htmlConteudo = '';
function echo_cont($html){
global $htmlConteudo;
$htmlConteudo .= $html;
}
I decided to answer my own question with the ideas of contributors because the problem is not about the php feature, but the way I was investigating - and can happens with you reading my answer.
The issue is: the image displayed in browser is an interpretation of the data sent, as the information shown in developer window. Is not the original data, it is an attempt to make xml/html document from data. In this case, the original data need to be seen, previously from browser interpretation, and it can be with this simple function:
function strTag($xmlstr){
$str = str_replace('<', '<', $xmlstr);
$str = str_replace('>', '>', $str);
$str = str_replace(' ', ' ', $str);
return nl2br($str);
}
Than, the data is captured:
ob_start();
include("www_pc/conteudo_imagens.php");
$output = ob_get_contents();
ob_clean();
echo(strTag($output));
Now it is time to get close to the screen and examine all the details. In my case, there was some tags like this:
<div style="float:left;width:80px;height:120px;margin:0px 5px 5px 0px;>
You can see the quote missing at the end of style declaration (it happens coding late of the night). So when the browser try to rebuild the xml and make it's own interpretation, confusing the analysis when trying to find the error. I'd test in Safari and Firefox, so it is not browser failure, but browser AI limitation. Got to see the original code, AI only in movies!

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

Jquery POST and AJAX prepend double space to returned data

I am still struggling with this problem after about 2 weeks with no sign of a solution.
Any data that is returned by PHP using $.ajax or $.post always has two spaces added onto the returned data. I have trimmed the data being echoed in PHP to confirm it's not an issue with the server or my scripts.
e.g.
echo '{"id": "'.$myId.'"}';
Becomes:
' {"id": "'.$myId.'"}'
When viewing the returned data in inspector. This causes problems for my js scripts because they expect nothing returned when there is no error. Double space is returned which causes errors when there are actually none, which in turn stops other events from firing.
I am using Jquery 1.8.3.
Does anyone have any idea what is causing this extremely strange and annoying issue?
I am using NetBeans
I recall that this only started happening since I moved my app to a new server, but I don't see how that would have effected it in this way.
This may be helpful,
I think there is a whitespace in your script (may be from included files, but not sure). You can overcome this by clearing the output buffer, before you send the data to browser. The following code will demonstrate the idea.
<?php
ob_start();
echo ' '; // Possible whitespace (may be from included files)
----------
----------
if (YOUR_CHECK_FOR_AJAX_REQUEST) {
ob_end_clean();
$myId = 1;
echo '{"id": "'.$myId.'"}';
exit;
}
?>
There is chance that you've got whitespaces at the end of your included php files (to prevent it, skip ending ?> tag).
Also you should check if there is nothing in front of <?php and disable BOM in your UTF-8 files.
The data which is returned from the file would have spaces or you would have html tags. Remove all the tags, lines, spaces and at the end remove ?>
If you are returning data from test.php the file should look like as below
<?php
$myId = '1';
echo '{"id": "'.$myId.'"}';

How to print code generated by some function in php?

I have a code in my CMS that prints content:<?php print $content ?>
I would like to output the actual php and html code behind $content, ideally in the browser. What I mean here is not the result in the browser, but the actual code behind it.Is it possible at all?
EDIT: Just to explain further: I need to print the source code of $content. Basically this variable produce some html and php content. I would like to see the code it produces, change it and replace $content with my custom code. Ideally the source code should be printed in the browser, is there anny php function that does it?
First off install the Devel Module, it has a wonderful function called dpm() which will print the contents of any variable to the Drupal messages area.
Then you need to go into your theme's template.php file and implement hook_preprocess_page():
function mytheme_preprocess_page(&$vars) {
dpm($vars['content']);
}
That will print out the $content array before it's rendered into a string. In the same preprocess function you can also change $vars['content'] as you see fit, and the changes will be reflected in $content in page.tpl.php.
Hope that helps
What do you mean by 'the code'? I think what you want to do is not possible, unless you make some kind of quine it's not possible to output the actual php code of a php file when you run it.
If $content is something like:
$content = 3 + 4 + 5;
echo $content; will output 12 yes? But I'm taking it you want to output 3 + 4 + 5 or something along those lines. The thing is, PHP (although it doesn't feel like it) is compiled. In this trivial example, 3 + 4 + 5 is stored exactly nowhere in your compiled program, it is stored as 12 (since it's static). More complex lines of code will be stored as pointers, values etc., all in nicely obfuscated machine code. Getting back to the 3 + 4 + 5 requires reading the input file and outputting the relevant line, which is difficult (think about what happens if you add or remove some lines, or how your running program knows where in the source file it is, or even if it's in the right source file).
tl;dr: this is not possible.
Well, if you just want to see html source for $content, you should simply use htmlspecialchars :
echo htmlspecialchars($content);
http://php.net/htmlspecialchars
or http://php.net/htmlentities

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