PHP eval code and store the result into a variable - php

I have continued my voyage into creating a extremely simple template engine.
Because I wanted to add logic to my template I eventually got back to the point that I allowed PHP tags into my code which I enabled by evalling the code.
Maybe not the best solution but when looking at the WordPress templates I noticed that the idea itself may not be that bad.
But now there still is one small problem left.
And that is that I want to translate the generated code.
But it has been evalled already. Hence parsed.
I thought of solving this problem by using ob_get_contents().
But this brought one more question and in case of errors it shows a white screen. (memory usage etc.)
Plus it still did not take away the problem of eval that it parsed the contents when evalled.
In short the class logic is:
Loading template files
Adding the contents
Compiling the template
Eval the code (but unfortunately also displaying the code)
Translate the code so I can translate the code parsed by a PHP script
I would love something like:
$code = eval('?>'.$tpl.'<?php');
$code = translate($code);
WriteCache($code);
SetDocumentHeader();
echo $code;
Would anyone know how to achieve this?
Thanks in advance!

$code = eval($tpl);
Check this out.

Related

How to gather code to be used in a htmlentities() function without rendering beforehand?

To put my question into context, I'm working on an entirely static website where 'post' pages are created by myself manually - there's no CMS behind it. Each page will require a <pre> <code> block to display code as text in a styled block. This could be very few - several which is why I'm trying to do this for ease.
Here's what I've done -
function outputCode($code) {
return "<pre class='preBlock'><code class='codeBlock'>".htmlentities($code)."</code></pre>";
}
The code works as expected and produces an expected outcome when it's able to grab code. My idea is to somehow wrap the code for the code block with this function and echo it out for the effect, fewer lines and better readability.
As I'm literally just creating pages as they're needed, is there even a way to create the needed code blocks with such function to avoid having to manually repeat all the code for each code block? Cheers!
EDIT:
I was previously using this function and it was working great as I was pulling code from .txt documents in a directory and storing the code for code blocks in a variable with file_get_contents(). However, now, I'm trying to get the function to work by manually inputting the code into the function.
Well. Wrapping the function input in ' ' completely slipped my mind! It works just fine now!
If I understand correctly, you want to re-use your outputCode function in several different PHP files, corresponding to posts. If yes, you could put this 1 function in its own file, called outputcode.php for example, and then do
include "outputcode.php";
in every post/PHP file that needs to re-use this function. This will pull in the code, from the one common/shared file, for use in each post/PHP file that needs it. Or maybe I'm misreading your last paragraph :(

Are there any limitations on where PHP code can go inside a file?

Can you put PHP anywhere in a file? Inside tags and quotes? For example, is something like this guaranteed to work (even though it isn't always recognized by an IDE's syntax highlighter):
<tr><tbody <?php if(!$row) echo "style='display: none;'"; ?>>
<!-- stuff that we only want to show if $row exists -->
</tbody></tr>
Or for example:
<a href="http://www.google.com/search?q=<?= echo $searchTerm; ?>"</a>
I know I can test this sort of thing on my machine, but I'm wondering if it is guaranteed/defined behavior and if there are any edge cases that don't work that I've missed.
Also, is there good reason not to do this? Is it dangerous because the next person looking at the code might miss it? Should I put a comment in? Does having to add a comment defeat the purpose of this method - succinctness?
Yes you can put the php tags anywhere in the page (html) there is no stopping you on that.
If we go under the hood, your web server sends the code to the php interpreter via a handler and merges the output with your static html file and sends the merged file as the response.
To add to my answer, developers usually go for MVC based frameworks so that the php code inside html page is restricted to only printing the variables and the business logic is performed in the controllers. I personally prefer CakePHP. Apart from that you might not want to put code that manipulates session or performs redirection between html tags else you will recieve the headers already set error as you have already printed certain html code before modifying the headers.

Any way to subvert class redeclaration issue? No namespaces

Heads up: I dont have the possibility to rename the classes or use name spaces for this.
Im looking for any crazy way to subvert class redeclaration issues in php. I actually only need 3 static variables from a web application, but the only way to get them requires including a file that declares a user class. However I already have a user class, so I get an error.
I tried to no avail to include the file in a class hoping it would isolate the included file - But no.
I tried reading an interface file I created that just echos the 3 values, but that actually just reads the php code and not the rendered values.
Is there anything like an opto-isolation system for code?
The only think I can think of is using ajax to do it, but it seems super sketchy. Is there a plain php version of this?
(Was a comment, but got too long.) Doesn't sound doable with your constraints. (You might need to show some code.) -- But if you are asking for a crazy way, and the option to rename the classes just applies to not editing the php script, then:
Load the include file into a variable, then transform it, and finally eval:
$source = file_get_contents("user.php");
$source = str_replace("class user", "class workaround_123", $source);
eval($source); // will give you a workaround_user instead of class conflict
Someone will probably comment on the advisability of eval... But it foremost depends on your code/situation if that's an applicable wacky workaround.
Alternatively you could invoke the user fetching code with a separate PHP process :
exec("QUERY_STRING=user=123 php-cgi user.php");
You could tokenize the whole file and go through it "by hand" to find the values you need.

Why is javascript not able to use a javascript variable I declared in a php file?

Hey everybody, this issue has had me stumped for the last week or so, here's the situation:
I've got a site hosted using GoDaddy hosting. The three files used in this issue are index.html , milktruck.js , and xml_http_request.php all hosted in the same directory.
The index.html file makes reference to the milktruck.js file with the following code:
<script type="text/javascript" src="milktruck.js"></script>
The milktruck.js file automatically fires when the site is opened. The xml_http_request.php has not fired at this point.
On line 79 out of 2000 I'm passing the variable "simple" to a function within the milktruck.js file with:
placem('p2','pp2', simple, window['lla0_2'],window['lla1_2'],window['lla2_2']);
"simple" was never initialized within the milktruck.js file. Instead I've included the following line of code in the xml_http_request.php file:
echo "<script> var simple = 'string o text'; </script>";
At this point I have not made any reference whatsoever to the xml_http_request.php file within the milktruck.js file. I don't reference that file until line 661 of the milktruck.js file with the following line of code:
xmlhttp.open('GET',"xml_http_request.php?pid="+pid+"&unLoader=true", false);
Everything compiles (I'm assuming because my game runs) , however the placem function doesn't run properly because the string 'string o text' never shows up.
If I was to comment out the line of code within the php file initializing "simple" and include the following line of code just before I call the function placem, everything works fine and the text shows up:
var simple = 'string o text';
Where do you think the problem is here? Do I need to call the php file before I try using the "simple" variable in the javascript file? How would I do that? Or is there something wrong with my code?
So, we meet again!
Buried in the question comments is the link to the actual Javascript file. It's 2,200 lines, 73kb, and poorly formatted. It's also derived from a demo for the Google Earth API.
As noted in both the comments here and in previous questions, you may be suffering from a fundamental misunderstanding about how PHP works, and how PHP interacts with Javascript.
Let's take a look at lines 62-67 of milktruck.js:
//experiment with php and javascript interaction
//'<?php $simpleString = "i hope this works"; ?>'
//var simple = "<?php echo $simpleString; ?>";
The reason this never worked is because files with the .js extension are not processed by PHP without doing some bizarre configuration changes on your server. Being on shared hosting, you won't be able to do that. Instead, you can rename the file with the .php extension. This will allow PHP to process the file, and allow the commands you entered to actually work.
You will need to make one more change to the file. At the very top, the very very top, before anything else, you will need the following line:
<?php header('Content-Type: text/javascript'); ?>
This command will tell the browser that the file being returned is Javascript. This is needed because PHP normally outputs HTML, not Javascript. Some browsers will not recognize the script if it isn't identified as Javascript.
Now that we've got that out of the way...
Instead I've included the following line of code in the xml_http_request.php file: <a script tag>
This is very unlikely to work. If it does work, it's probably by accident. We're not dealing with a normal ajax library here. We're dealing with some wacky thing created by the Google Earth folks a very, very long time ago.
Except for one or two in that entire monolithic chunk of code, there are no ajax requests that actually process the result. This means that it's unlikely that the script tag could be processed. Further, the one or two that do process the result actually treat it as XML and return a document. It's very unlikely that the script tag is processed there either.
This is going to explain why the variable never shows up reliably in Javascript.
If you need to return executable code from your ajax calls, and do so reliably, you'll want to adopt a mature, well-tested Javascript library like jQuery. Don't worry, you can mix and match the existing code and jQuery if you really wanted to. There's an API call just to load additional scripts. If you just wanted to return data, that's what JSON is for. You can have PHP code emit JSON and have jQuery fetch it. That's a heck of a lot faster, easier, and more convenient than your current unfortunate mess.
Oh, and get Firebug or use Chrome / Safari's dev tools, they will save you a great deal of Javascript pain.
However...
I'm going to be very frank here. This is bad code. This is horrible code. It's poorly formatted, the commenting is a joke, and there are roughly one point seven billion global variables. The code scares me. It scares me deeply. I would be hesitant to touch it with a ten foot pole.
I would not wish maintenance of this code on my worst enemy, and here you are, trying to do something odd with it.
I heartily encourage you to hone your skills on a codebase that is less archaic and obtuse than this one before returning to this project. Save your sanity, get out while you still can!
perhaps init your values like this:
window.simple = 'blah blah blah'
then pass window.simple
You could try the debugger to see what is going on, eg. FireBug

PHP: Where should I store the text for info & warning messages

I have a question concerning the design of my project's Code.
In most cases, it is important to separate content from code (HTML mixed with PHP in bigger apps=No good idea, etc.) but how should I handle things like the text of error messages?
Assuming this one message will be only used in one case/PHP file:
MessageBox( 'Something gone wrong, probably your fault' );
or
MessageBox( Lang::error_usersfault );
(Where Lang is a class located in some config file, full of consts)
If you have any experiences (I think every PHP programmer will come across something like this) with things like in the example above - What are they? How do you solve it?
What is the better solution?
May be you'll find php extension gettext useful?
MessageBox(_("Have a nice day"));
PHP Manual of Gettext::gettext

Categories