Php problem eval/html/php - php

I've been writing a php/html page encoder/decoder... I know it already exists but it's a university project so go on XDDD
I encode the pages that I want to protect let's say hypothetically with base64_encode and when I receive a request of any pages I have a loader that reads the coded page, decrypts it and with eval executes it. The real problems arise when I try to decrypt and execute a mixed php/html page. Obviously eval can't execute html code so my question is do I really become crazy about splitting the page executing the php code and print the html? And also if I include an encoded php or php/html page do I really have to reuse the method up here?
I hope someone can really help me because i have a week left before the deadline and I can't change the project at this point.
chris here the function and the fisrt calling in $param[0] i've got the filename called
function MyInclude($filename)
{
// create the temp file
$temp_filename = "tmp.php";
$handle = fopen($temp_filename , 'w+');
if (!$handle)
die('Error creating temp file');
// write the decrypted data, close the handle
$tmp=file_get_contents($filename);
$data=MCrypt_Decode($tmp,'PFL_EPU_V100_mia');
fwrite($handle,$data );
fclose($handle);
// start output buffering to contain any output the script creates
ob_start();
try {
include($temp_filename);
} catch (Exception $e) {
die('There was an error in the encrypted file, cannot process');
}
// get the output, clear the buffer
$output = ob_get_contents();
ob_end_clean();
//destroy the temp file
unlink($temp_filename);
// now you can output the buffer, if desired:
echo $output;
}
MyInclude($param[0]);
the $param[0] file here
<?php
session_start();
$_SESSION['title']='Home';
MyInclude("header.php");
?>
<body>
sono il body <?php echo APP_PATH; ?>
</body>
<?
echo "boss";
MyInclude("footer.php");
?>
any idea about it??? or you need some other code??? let me know T_T
Mike

You can eval() a string that contains mixed html and php, just so long as the tags are included.
http://php.net/manual/en/function.eval.php

When eval() encounters a php close tag (?>), it will stop trying to treat it as php code and just echo everything out until it comes to a php open tag.
The typical solution to your problem is something like this:
$file = ... //Your decoded php/html code here
$file = '?>' . $file; //Add a close tag to the beginning;
ob_start();
eval($file);
$output = ob_get_clean();
echo $output; //Or do something else with it... really, if you're
//just going to be echoing it you can skip the output buffering

Is it possible to decrypt the page, write it to a file, then include it? That would let the PHP interpreter do what it does best - interpret PHP documents. That will include HTML/PHP combinations without relying on eval.
The outline of that would be:
// create the temp file
$temp_filename = "tmp.php";
$handle = fopen($filename , 'w');
if (!$handle)
die('Error creating temp file');
// write the decrypted data, close the handle
fwrite($handle, $decrypted_data);
fclose($handle);
// start output buffering to contain any output the script creates
ob_start();
try {
include_once($temp_filename);
} catch (Exception $e) {
die('There was an error in the encrypted file, cannot process');
}
// get the output, clear the buffer
$output = ob_get_contents();
ob_end_clean();
//destroy the temp file
unlink($temp_filename);
// now you can output the buffer, if desired:
echo $output;
Function references
fopen: http://us2.php.net/manual/en/function.fopen.php
fwrite: http://us2.php.net/manual/en/function.fwrite.php
fclose: http://us2.php.net/manual/en/function.fclose.php
ob_start: http://us2.php.net/manual/en/function.ob-start.php
ob_get_contents: http://us2.php.net/manual/en/function.ob-get-contents.php
ob_end_clean: http://us2.php.net/manual/en/function.ob-end-clean.php
unlink: http://www.php.net/manual/en/function.unlink.php

You will need dump the decoded file to another file and include(); it. The eval approach will not work because it will exit with a parse error if the first item in the file is not either an opening <?php tag, or a valid bit of PHP code.
More than this, you will need to find/replace any occurences of include(), require(), include_once(), and require_once() within the encrypted file with a different function, to ensure you don't try to execute another encrypted file before it has been decrypted. You could do this at execution (ie decryption) time, but it would be much better to it a encryption time, to minimise the time required to pre-fetch the code before it is executed.
You can define these customised functions to decrypt a file and include/require it in your loader script.

Your problem description is a bit vague however your problem seems to be solvable with output buffering.

Have you tried decrypting the page, then parsing the text to split out anything between and then only executing that code?

Related

Get current page name with file created by a PHP file

So I have a page called create.php that creates another php file called "1". In this php file called "1". I was hoping to use
<?php echo $_SERVER['PHP_SELF'];?>
or
<?php $path = $_SERVER["SCRIPT_NAME"];echo $path;?>
To create a link that would take the number of the page and +1 it. When I do both of these functions instead of getting what I would think I would get, "1", I get "create", the page that it was created with. I'm quite dumbfounded by why this is happening, the code is most definitely on "1" and I even double checked to make sure create made a file and that I was on it so why does it think the current page is "create"?
Code being used
<?php
// start the output buffer
ob_start(); ?>
<?php echo $_SERVER['PHP_SELF'];?>
<?php
// open the cache file "cache/1" for writing
$fp = fopen("cache/1", 'w');
// save the contents of output buffer to the file
fwrite($fp, ob_get_contents());
fclose($fp);
ob_end_flush();
?>
You split the code in pieces and you probably have a wrong idea about what happens and what will be written in cache/1. Your code is the same as the following:
<?php
// start the output buffer
ob_start();
// echo the path of the current script
echo $_SERVER['PHP_SELF'];
// open the cache file "cache/1" for writing
$fp = fopen("cache/1", 'w');
// save the contents of output buffer to the file
fwrite($fp, ob_get_contents());
fclose($fp);
ob_end_flush();
I removed the closing PHP tag (?>) when it was followed by an open PHP tag (<?php).
Now it should be clear that, without output buffering, the script create.php display its own path relative to the document root. The output buffering captures the output and puts it into file cache/1.
You don't even need output buffering for this. You can simply remove all the calls to ob_* functions, remove the echo() line and use:
fwrite($fp, $_SERVER['PHP_SELF']);
It's clear that this is not your goal. You probably want to generate a PHP file that contains the following content:
<?php echo $_SERVER['PHP_SELF'];?>
This is as simple as it putting this text into a string and writing the string to the file:
<?php
$code = '<?php echo $_SERVER["PHP_SELF"];?>';
$fp = fopen("cache/1", 'w');
fwrite($fp, $code);
fclose($fp);
You can even use the PHP function file_put_contents() and all the code you posted in the question becomes:
file_put_contents('cache/1', '<?php echo $_SERVER["PHP_SELF"];?>');
If you need to put a bigger block of PHP code in the generated file then you can use the nowdoc string syntax:
$code = <<<'END_CODE'
<?php
// A lot of code here
// on multiple lines
// It is not parsed for variables and it arrives as is
// into the $code variable
$path = $_SERVER['PHP_SELF'];
echo('The path of this file is: '.$path."\n");
$newPath = dirname($path).'/'.(1+(int)basename($path));
echo('The path of next file is: '.$newPath."\n");
// That's all; there is no need for the PHP closing tag
END_CODE;
// Now, the lines 2-11 from the code above are stored verbatim in variable $code
// Put them in a file
file_put_contents('cache/1', $code);

How to process PHP code in a text string, to prevent it from being seen as text?

I'm using the Redactor editor in a custom built CMS. Redactor has an option, phpTags, which when set to true allows PHP code to be entered and saved as part of the content.
The issue is that this PHP code is being seen as text, not PHP code, and is being escaped rather than being processed.
For example, if I enter this in the editor:
<?php echo date('Y'); ?>
Instead of the year being displayed, the code is commented out in the page's markup, like so:
<!--?php echo date('Y'); ?-->
How can I prevent this from happening? To make sure the PHP code is processed/interpreted as such by the server?
I should probably mention that there are a lot of people using this CMS, so there's no way to know what PHP code may be added in advance.
Perhaps
<!-- <?php echo date('Y') ?> -->
You can't change PHP's opening/closing tags like you are, not without a recompile of PHP. If you want to hide php's output, then surround the entire php code block with html comment tags.
PHP won't care about the html comments. It couldn't care at all what it's embedded in. You could stuff a PHP code block into the middle of a .jpg file and it'd still execute, as long as the webserver's configured to run .jpg files through the PHP interpreter.
To fix this issue I took the content I was previously just displaying via echo, and saved it to a temporary file.
Then I turned on output buffering, included that temporary file in the PHP script, and grabbed its contents via ob_get_contents().
This allowed me to display the content with all the PHP within having been parsed. Here's the code for reference:
// Create path to temporary file
$tmpPath = '/temp.php';
// Set file variable to null for error checking
$tmpFile = NULL;
// Try creating the temporary file
if ( $tmpFile = fopen($tmpPath, 'w') ) {
if ( fwrite($tmpFile, $postContent) === FALSE ) {
// Do something if the file can't be written to
} else {
// Close file
fclose($tmpFile);
}
}
// Start output buffereing
ob_start();
// Include the temporary file created above
include $tmpPath;
// Save buffered contents to a variable
$content = ob_get_contents();
// End output buffering
ob_end_clean();
// Display content
echo $content;
I appreciate the various comments to my question, as it helped prod me in the right direction to getting this figured out.

Editing a PHP File, with another php file, using Fwrite

My last question wasn't explained very well.
What I'm trying to do here is insert data into a PHP File, Using the fwrite feature on another .php file.
To keep this simple, I'm labelling the one I want data inserted as file.php and the one I'm using fwrite to execute on, is edit.php
Now, I got the writing thing down, what my problem is, is I need to INSERT that data, Before the closing php tag on file.php.
What I tried doing was, deleting the closing php tag, writing the data, and then rewriting the tag.
Here is my source code for that:
<?php
$rows = file("file.php");
$tagremove = "?>";
foreach($rows as $key => $row) {
if(preg_match("/($tagremove)/", $row)) {
unset($rows[$key]);
}
}
file_put_contents("file.php", implode("", $rows));
$User = $_GET["user"];
$File = "file.php";
$Handle = fopen($File, "a");
fwrite($Handle, "");
fwrite($Handle, $User);
fwrite($Handle, "\r\n");
fwrite($Handle, "?>");
print "Data Written";
fclose($Handle);
?>
When I run this on Edit.php, it inserts that data into the file, but its only writing to the first line, and replacing whatever is already there. (In my case its the opening php tag). I don't know what I'm doing wrong, or if there is another way to do this, but any assistance would be appreciated.
Edit: this is again for a chat client.
I'm having a file, that sends a message into a .txt file that the client then reads.
And that file is reading file.php (staff.php) to check if the user submitting is a staff member.
If it comes up true that the user is a staff member, then it changes the username variable in the send.php.
And so far, the send.php has only sucessfully, included the Staff.php, I've tried staff.txt, and the reason is, php code is in the staff.php.
Try this:
$data="echo 'hello world!';";
$filecontent=file_get_contents('file.php');
// position of "?>"
$pos=strpos($filecontent, '?>');
$filecontent=substr($filecontent, 0, $pos)."\r\n".$data."\r\n".substr($filecontent, $pos);
file_put_contents("file.php", $filecontent);
Please don't forget, that you need to check data from user.
Ok much better alternative use a data file. Ill use json because its easy to use an very easy to parse by human eyes as well:
// read file
$data = file_get_contents('data.json');
$json = json_decode($data, true);
// manipulate data
$json['users'][] = $_GET['user'];
// write out file
$dataNew = json_encode($json);
file_put_contents('data.json', $dataNew);
the reason is, php code is in the staff.php
Well this isnt something you workaround. You should be writing/reading this kind of information form a data stor - that could be a file or a database... but not an actual script.

PHP ob_start not working

I am new to PHP and Code Ignitor, Facing some issue while trying to convert dynamic data content into static html file. This is code snippet. when i request code snippet file it prints only Error 111111111 nothing else. not able to understand what is the error here.
This is my original Code and here am trying to generate static html file with dynamic content. It doesn't works for me
<?php
echo "Error 111111111";
ob_start();
$fileName = "sample.html";
?>
<html>
<body>
Some html is here
</body>
</html>
<?php
try{
$output = ob_get_contents(); // get contents of trapped output
//write to file, e.g.
$newfile = $fileName;
$file = fopen ($newfile, "w");
fwrite($file, $output);
fclose ($file);
ob_end_clean(); // discard trapped output and stop trapping
}catch (Exception $ex){
echo "Error ".$ex->getMessage();
}
?>
I don't see an error?
ob_start() suppresses all output until ob_flush() is called. You're not calling ob_flush(), so nothing after the ob_start() will be output. That's what you're seeing, and that's exactly the way it's supposed to work.
I suppose the real question is what were you trying to achieve?
The code snippet is quite confusing, because ob_start() doesn't generate any exceptions, yet you've put it into a try / catch block. Your catch section will never be called because nothing in the try block will ever generate any exceptions.
So what were you trying to do here? The answer to that may help us give you more guidance.
ob_start marks where buffered output should begin, but AFAIK you also have to tell PHP to end buffering and output the current contents: ob_end_flush()

Streaming output to a file and the browser

So, I'm looking for something more efficient than this:
<?php
ob_start();
include 'test.php';
$content = ob_get_contents();
file_put_contents('test.html', $content);
echo $content;
?>
The problems with the above:
Client doesn't receive anything until the entire page is rendered
File might be enormous, so I'd rather not have the whole thing in memory
Any suggestions?
Interesting problem; don't think I've tried to solve this before.
I'm thinking you'll need to have a second request going from your front-facing PHP script to your server. This could be a simple call to http://localhost/test.php. If you use fopen-wrappers, you could use fread() to pull the output of test.php as it is rendered, and after each chunk is received, output it to the screen and append it to your test.html file.
Here's how that might look (untested!):
<?php
$remote_fp = fopen("http://localhost/test.php", "r");
$local_fp = fopen("test.html", "w");
while ($buf = fread($remote_fp, 1024)) {
echo $buf;
fwrite($local_fp, $buf);
}
fclose($remote_fp);
fclose($local_fp);
?>
A better way to do this is to use the first two parameters accepted by ob_start: output_callback and chunk_size. The former specifies a callback to handle output as it's buffered, and the latter specifies the size of the chunks of output to handle.
Here's an example:
$output_file = fopen('test.html', 'w');
if ($output_file === false) {
// Handle error
}
$write_ob_to_file = function($buffer) use ($output_file) {
fwrite($output_file, $buffer);
// Output string as-is
return false;
};
ob_start($write_ob_to_file, 4096);
include 'test.php';
ob_end_flush();
fclose($output_file);
In this example, the output buffer will be flushed (sent) for every 4096 bytes of output (and once more at the end by the ob_end_flush call). Each time the buffer is flushed, the callback $write_ob_to_file will be called and passed the latest chunk. This gets written to test.html. The callback then returns false, meaning "output this chunk as is". If you wanted to only write the output to file and not to PHP's output stream, you could return an empty string instead.
Pix0r's answer is what you want unless you actually need it "included" rather than just executed. For example, if you have login information before the test.php, it will not get passed into the file if you call it with fopen.
If you need it genuinely included, then what you have is the simplest method, but if you want constant output, you'll need to actually write test.php in a manner that outputs as well as stores the information as it goes. As far as I know there's no way to both collect buffer and output it as you go.
Here you go x-send-file, use mod_xsendfile to send file efficiently, really easy.

Categories