String variable to execute PHP code - php

What I want to do is pull html and PHP code out from a database and then execute it. So for example I may have:
<?php
$test = <<<END
<p> <?php
echo time();
?> </p>
END;
echo $test;
?>
What I want is to get $test to print
<p> 12:00PM </p> //right
instead of printing:
<p> <?php echo time(); ?> </p> //wrong
as occurs when I use the echo function.
Please do not tell me how to do the same thing with JavaScript or other work around. Instead stick to the question and remember the example is just an example to demonstrate my problem. The actual code is much more complicated.
I have looked at Javascript string variable that contains PHP code but none of the answers work.
Thanks,
Brett

I would strongly recommend against doing what you're asking to do. There are a number of very good reasons for this.
The answer to the question, as others have said, is to use eval(). However, eval() has several major issues with it.
Firstly, to follow-up from the comments on the question, code run through it is executed significantly slower than regular PHP code. Although PHP is a scripted language, it does have optimisations to make run faster. None of these optimisations work for an eval block, because the scripting engine can't know what the code will look like until it actually runs it.
Not only that, but loading the code from the database will also be slower than loading it from a file using a regular include() statement.
Secondly, eval() is one of the biggest security headaches you can have. An eval() statement will run any PHP code it is given, which means that an attacker can manipulate the code will be able to do anything on your server. In short, a single eval() statement in your code can turn a minor hack into a catastrophic one.
One alternative solution that doesn't involve changing your concept too much would be to save the PHP code to a file rather than the DB. This would allow you to simple include() it at the appropriate time, and would eliminate the speed issues discussed above. You could still use the DB to store it if you wished, and have it export to a cache file using a cron job or similar, or you could just save it directly to the file.
However, this solution wouldn't necessarily eliminate the security risks. You would still be running effectively arbitrary code, which would still mean that a hacker could do a lot of damage with a relatively simple hack.
I would therefore recommend re-thinking why you need to allow user-input PHP code to be entered into your software.

You can use eval() for this
$test = <<<END
<p> <?php
echo time();
?> </p>
END;
ob_start();
eval("?>$test");
$result = ob_get_clean();

Something like this might be useful...
<?php echo writedata($code_to_parse); ?>
<?php
function writedata($data){
if(substr($data,0,2)=="?>"){
eval($data);
// eval will run & echo the code immediately, so return an empty $code
$code="";
}else{
$code="$data";
}
return $code;
}
?>
Now you can handle either plain html & mixed php/html with one function call.
Sample data:
?>Bonjour. The time now is <?php echo $timenow; ?> in Paris.
<div class="bluebox">Perfect day for swimming</div>
There are some side effects using eval(), remember it will execute as soon as to call it, so can sometimes have unexpected results.

Related

pulling and outputing php tags from a database

I am trying to create a dynamic FAQ page. I have the following phtml sample :
<div id="faq">
<!-- Start FAQ "Navigation" -->
<div class="faqBox">
<? foreach($this->aFAQ as $k => $val) : ?>
<?= ($val['mQuestion']); ?>
<?= ($val['mAnswer']); ?>
<? endforeach; ?>
</div>
</div>
Which outputs as follows:
For additional payment options - check or money order, please contact us at iBrandingLevel == 2 ? $this->oStore->getSuppPhone()." Monday to Friday ".$this->oStore->getSuppHoursOpen()." - ".$this->oStore->getSuppHoursClose()." ".$this->oStore->getSuppTimeZone() : "(888) 455-3237 x2 from Monday to Friday 8:00am - 4:30pm MST/Arizona."; ?>
The above text is just the first $val['mAnswer'] (I didnt include the question as that is working properly).
The html is being rendered however obvoiusly the php isn't. the <? and ?> are being removed and just code is displaying. Is there a fix for this? or is my approach fundamentally wrong.
thanks
Your approach is fundamentally wrong, you are outputting PHP code as if it was HTML text and try to execute it.
It is possible to execute code from a string, you can look at the Eval method (http://php.net/manual/fr/function.eval.php) in PHP, but it is not recommended to do this. There are better ways to resolve your specific issues than to output PHP code directly.
What you could do is send a few variables to the view, and use if conditions there.
You could also prepare the full string you need before the view and then all that would be needed is to display it.
To elaborate a little about Eval :
1- If the code you execute within the Eval comes from a user, it is extremely dangerous.
2- If not, there is very often a better solution to the problem, using Eval makes it harder to debug.
Actually, I'm not sure I should answer this.
First, the answer to your request is the mixed eval ( string $code ) php function.
Second, FORGET IT. IMHO, this could be one of the most dangerous things you could think in.
Thanks everybody for the input and resulting discourse. The php code that was being stored in the database was not being input by users, it was all completely internal, however it still shouldn't be there.
I ultimately went through the database and set a %%variablename%% in place of the php code and then upon retrieval I wrote a script that would:
preg_replace("/\%\%variablename\%\%/", $desiredPhpcode, dbRetrievedString).
all instances of %%variablename%%.
It seemed the safer and more sound approach. I don't know if this is an IDEAL approach that anybody else could benefit from if caught in this circumstance or if it 'just works', but I thought I would share.
Thanks Again for the input it helped enormously
PHP is server-side language. Outputting it to client does not make any sense, as there is no one to interpret it.

PHP' if' spanning in different code blocks

Ok, someone has just shown me a piece of PHP code and at the end of the file I've seen a stray <?php } ?> . I thought that should give a compilation error, but it doesn't.
Why is:
<?php
if(1==1){
?>
X
<?php } ?>
valid?
Is it safe to split a statement into multiple php blocks?
PS: I was expecting for something more from the answers then "yes" :D
Yes that is fine, but I would suggest:
<?php if(1==1):?>
X
<?php endif; ?>
It makes it a little more readable then random { and }
From the manual:
Everything outside of a pair of opening and closing tags is ignored by
the PHP parser which allows PHP files to have mixed content. This
allows PHP to be embedded in HTML documents, for example to create
templates.
Welcome to the mysterious world of PHP.
Safe? Yes.
Readable? Not really.
Avoid mixing your PHP logic with your HTML where possible. There are few times when this is a good idea, as it makes reading through and understanding your code difficult.
Yes, this is fine.
It's often useful to drop out of "php mode" for large blocks of HTML - you'll see this technique used anywhere HTML and PHP are mixed.
It is valid, but not recommended if you want to have a code that is maintainable and readable in the long run.
You must bear in mind that every time you "exit" from PHP, you are entering HTML.

Performance difference between these methods

Is there any advantages/disadvantages to either of these statements over the other one:
<?php
$test = 1;
$test2 = 2;
$test3 = $test + $test2;
echo "<p>Hello World</p>";
?>
OR
<?php
$test = 1;
$test2 = 2;
$test3 = $test + $test2;
?>
<p>Hello World</p>
What i'm asking is, if i'm outputting a page using PHP should i keep closing the php tags and stick normal HTML in or echo out the HTML? Which is better?
if you want do be realy exact, there are three options:
the slowest:
echo "<p>Hello World</p>";
a bit faster (no need to check for inline-valiables because of single quotes):
echo '<p>Hello World</p>';
the fastest (no php-interpreting at all):
<p>Hello World</p>
but between all of this, the difference would be so minimalistic that you won't ever notice it - much more important: make your code redable and do it the same way everywhere, so nobody who's reading your code (and has to maintain it) gets confused. i personally would prefer the third method (so i can use code-completition in my IDE), but it's your choice - i know a lot of people who output everything using echo.
EDIT: to be complete, there are some more possibilitys i didn't mentioned like heredoc- and nowdoc-syntax, but this are basically the same as double/single-quotes... also, you could write print instead of echo and so on, but that wouldn't make a difference.
Method 2 is cleaner IMHO because you separate PHP code from HTML. Your IDE (if you use any) can parse your HTML tags and autocomplete them, and spot any typo's.
I'm not a PHP programmer but I would assume the 2nd method is faster, because PHP doesn't have to process the echo language construct, allocate buffer and all that stuff. It is also cleaner, and less of a hassle to modify the HTML.
Also, it would be wise to learn to use a template engine for your HTML in order to separate concerns. Smarty was popular a couple years ago, I don't know if it's still is.
Although the difference is negligible, you should stick normal outputing out of PHP tags. Echo command will have to be parsed by PHP interpreter and then sent as output.
The only difference is that with echo(); you instruct PHP to process the code, otherwise, there is no difference at all.
One way or another, the result is exactly the same and for performance, there is almost no differences at all. Like... How much time PHP needs to process that echo();? I think with miliseconds you could run in problems calculating numbers that small. Hehe.

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));

PHP - To echo or not to echo?

What is more efficient and/or what is better practice, to echo the HTML or have many open and close php tags?
Obviously for big areas of HTML it is sensible to open and close the php tags. What about when dealing with something like generating XML? Should you open and close the php tags with a single echo for each piece of data or use a single echo with the XML tags included in quotations?
From a maintenance perspective, one should have the HTML / XML as separate from the code as possible IMO, so that minor changes can be made easily even by a non-technical person.
The more a homogeneous block the markup is, the cleaner the work.
One way to achieve this is to prepare as much as possible in variables, and using the heredoc syntax:
// Preparation
$var1 = get_value("yxyz");
$var2 = get_url ("abc");
$var3 = ($count = 0 ? "Count is zero" : "Count is not zero");
$var4 = htmlentities(get_value("def"));
// Output
echo <<<EOT
<fieldset title="$var4">
<ul class="$var1">
<li>
$var2
</li>
</ul>
</fieldset>
EOT;
You will want to use more sensible variable names, of course.
Edit: The link pointed out by #stesch in the comments provides some good arguments towards using a serializer when producing XML, and by extension, even HTML, instead of printing it out as shown above. I don't think a serializer is necessary in every situation, especially from a maintenance standpoint where templates are so much more easy to edit, but the link is well worth a read. HOWTO Avoid Being Called a Bozo When Producing XML
Another big advantage of the separation between logic and content is that if transition to a templating engine, or the introduction of caching becomes necessary one day, it's almost painless to implement because logic and code are already separated.
PHP solves this problem by what is known as heredocs. Check it out please.
Example:
echo <<<EOD
<td class="itemname">{$k}s</td>
<td class="price">{$v}/kg</td>
EOD;
Note: The heredoc identifer (EOD in this example) must not have any spaces or indentation.
Whichever makes sense to you. The performance difference is marginal, even if a large echo is faster.
But an echo of a big string is hard to read and more <?php echo $this->that; ?> tell a story :)
echo sends its argument further down the request processing chain, and eventually this string is sent to the client through a say, network socket. Depending on how the echo works in conjunction with underlying software layers (e.g. webserver), sometimes your script may be able to execute faster than it can push data to the client. Without output buffering, that is. With output buffering, you trade memory to gain speed - you echos are faster because they accumulate in a memory buffer. But only if there is no implicit buffering going on. One'll have to inspect Apache source code to see how does it treat PHPs stdout data.
That said, anything below is true for output buffering enabled scripts only, since without it the more data you attempt to push at once the longer you have to wait (the client has to receive and acknowledge it, by ways of TCP!).
It is more efficient to send a large string at once than do N echos concatenating output. By similar logic, it is more efficient for the interpreter to enter the PHP code block (PHP processing instruction in SGML/XML markup) once than enter and exit it many times.
As for me, I assemble my markup not with echo, but using XML DOM API. This is also in accordance with the article linked above. (I reprint the link: http://hsivonen.iki.fi/producing-xml/) This also answers the question whether to use one or many PHP tags. Use one tag which is your entire script, let it assemble the resulting markup and send it to the client.
Personally I tend to prefer what looks the best as code readability is very important, particularly in a team environment. In terms of best practice I'm afraid I'm not certain however it is usually best practice to optimize last meaning that you should write it for readability first and then if you encounter speed issues do some refactoring.
Any issues you have with efficiency are likely to be elsewhere in your code unless you are doing millions of echo's.
Another thing to consider is the use of an MVC to separate your "views" from all of your business logic which is a very clean way to code. Using a template framework such as smarty can take this one step further leading to epic win.
Whatever you do, don't print XML!
See HOWTO Avoid Being Called a Bozo When Producing XML
I've made myself the same question long time ago and came up with the same answer, it's not a considerable difference. I deduct this answer with this test:
<?
header('content-type:text/plain');
for ($i=0; $i<10; $i++) {
$r = benchmark_functions(
array('output_embeed','output_single_quote','output_double_quote'),
10000);
var_dump($r);
}
function output_embeed($i) {
?>test <?php echo $i; ?> :)<?
}
function output_single_quote($i) {
echo 'test '.$i.' :)';
}
function output_double_quote($i) {
echo "test $i :)";
}
function benchmark_functions($functions, $amount=1000) {
if (!is_array($functions)||!$functions)
return(false);
$result = array();
foreach ($functions as $function)
if (!function_exists($function))
return(false);
ob_start();
foreach ($functions as $idx=>$function) {
$start = microtime(true);
for ($i=0;$i<$amount;$i++) {
$function($idx);
}
$time = microtime(true) - $start;
$result[$idx.'_'.$function] = $time;
}
ob_end_clean();
return($result);
}
?>

Categories