PHP eval() code in between <?php ?> from database - php

I want to be able to put PHP into the database and run it. I have to do this because I store page layouts in the database and each our different for each other, however in some cases I want to use dynamic content for some of the pages.
Assume $query_from_db is the string returned from the database. PHP should only eval() the code in between <?php and ?>
$query_from_db = '<div>
<?php
//php to run
function dosomething() {
//bleh
}
?>
</div>
';
php echo eval($query_from_db);
How can I do this? I'm aware this is not recommended.

I'm not arguing about the sense or nonsense of this approach. To some extend, this is a valid question.
See the documentation:
To mix HTML output and PHP code you can use a closing PHP tag to leave PHP mode.
So you have to do:
eval('?> ' . $query_from_db . ' <?php ');
DEMO
Also note that eval is outputting directly to the browser. It does not return a value. Have a look at Output Control Functions for buffering.

You are aware that this is not recommended and I strongly urge everyone to review the comments to this question.
But to provide an answer:
<?php
$string = 'hello <?php echo "world"; ?>';
eval('?>'.$string.'<?'); // will output "hello world";
be aware that this however will not work:
<?php
$string = 'hello <?php echo "world"; ?>';
eval('?>'.$string.'<?php'); // error will be thown
This works again:
<?php
$string = 'hello <?php echo "world"; ?>';
eval('?> '.$string.' <?php '); // will output "hello world";
i am not really sure why.
following up on your comment to grab the output you can do:
<?php
$string = 'hello <?php echo "world"; ?>';
ob_start();
eval('?> '.$string.' <?php '); // will output "hello world";
$output = ob_get_clean(); // $output will now contain "hello world". No text will have ben printed.

If you want to avoid the eval stigmata, you can alternatively use:
include("data:,$query_from_db");
It's just another name for eval which doesn't upset people as much. It depends on the php.ini setting allow_url_include however.
What you are doing is functionally equivalent to include("$template/$by_name.php"); and just differs in that you didn't put the database content into a file before. (But that's the other workaround: file_put_contents && include).

Related

How to echo php code and use it?

<?php echo $row["html"]; ?>
Inside of the $row["html"] there's:
<?php $Site->Nav($owner); ?>
but when I echo it, it only echoes:
Nav($owner); ?>
How may I print the full and make it usable, which means that it will print the function Nav?
I've tried to replace <?php with [[// i the database, and just before echoing it, I change back with replace. But without success
I think you need to use eval function of php. See the example below.
$string = 'cup';
$name = 'coffee';
$str = 'This is a $string with my $name in it.';
echo $str. "\n";
eval("\$str = \"$str\";");
echo $str. "\n";
Might be it can help.
Use eval function. It might solve your problem like this:
<?php echo eval($row["html"]); ?>
Keep the code as is in DB as if you are writing it in PHP file but without PHP opening and closing tags i.e. <?php and ?>. I haven't checked this (as i am not sure what $Site->Nav($owner); will do) but hope it would work in this case.
If I understand correctly you are wanting to output the results of $Site->Nav($owner);
I have no idea what this is expected to output, but assuming it is a string of some kind that you wish to display (hence echo) - an example of achieving this would be calling your code and have that method return the value, so you can echo it out. Ie:
function Nav($owner){
// Do your stuff
return 'Your Desired Output';
}
Then on your page you would have
<?php echo $Site->Nav($owner); ?>
Which would echo "Your Desired Output".

Is it possible to create a function in PHP called "echo"? [duplicate]

I recently looked at my source code and it was a real mess.
my php source:
echo '<h1>Rar<h1>';
echo '<span>Rar</span>';
echo '<p>Rar</p>';
and when I view the browser source for the page rendered:
<h1>Rar</h1><span>Rar</span><p>Rar</p>
is there a way for me to override echo so that every output would end with a newline, something like
function echo($string)
{
echo $string . "\r\n";
}
echo is not a function, but a language statement. It cannot be redefined. If you are looking to prettify your output markup, have look at Tidy.
What you could do, is use your IDE's search/replace method and replace all echo statements with echo PHP_EOL,. This would append the OS specific newline char(s) before any output. Note the comma after PHP_EOL as it is important.
You can output several values with echo like this:
echo 'one', $foo, PHP_EOL,
'two', $bar, PHP_EOL;
so there is no need to write echo on each line.
However, I agree with anyone who suggested using a more dedicated approach to separate content and layout e.g. using template views or HereDoc.
In additon, there is very little gain in having pretty markup. If you are using tools like Firebug to inspect the HTML, you will have properly formatted markup regardless of the mess the markup really is. Moreover, on sites with a lot of visitors, you'll often find the markup minified, which is the opposite of what you are trying to do, simply because all these newlines and tabs add to the weight of the page, which leads to slower page loads and increased traffic cost.
You have various possibilities to output HTML.
You can use the heredoc syntax:
$html = <<<EOF
<h1>Rar<h1>
<span>Rar</span>
<p>Rar</p>
EOF
echo $hml;
Or (what is way better in my opinion), separate HTML from PHP. E.g. put all the PHP logic in the top of the file and the HTML after the PHP block:
<?php
// all your PHP goes here
$foo = 'bar'
?>
<!-- HTML comes here -->
<html>
<body>
<div>Hello <?php echo $foo; ?> </div>
</body>
</html>
Variables can be printed as shown above. But these variables don't contain HTML.
When you have to output HTML based on a condition, you can use the alternative syntax for control statements:
<?php if($some_condition): ?>
<h1>Rar<h1>
<span>Rar</span>
<p>Rar</p>
<?php endif ?>
This way it is also easier to debug your HTML as it is not only a PHP string.
You can set up and output buffer and then run the buffer through htmltidy. The tidy extension even has a specific function for the purpose. Just call this before you start outputting your html:
ob_start('ob_tidyhandler');
Although this solution does not override echo, you can get something close to echo with a newline. Add:
function e() {
return o::singleton();
}
class o {
private static $instance;
public static function singleton()
{
if (!isset(self::$instance)) {
$className = __CLASS__;
self::$instance = new $className;
}
return self::$instance;
}
public function __set($prop, $txt) {
echo $txt . PHP_EOL;
}
}
to your file, and then you can use:
e()->o = "Line which ends in newline";
instead of echo.
Another solution would be to separate your code from your layouts by using a proper templating engine.
You can indirectly overload echo() by using the __toString() magic method like so:
<?php
class CleanOutput
{
public $content;
public function __construct($c) {
$this->content= $c;
}
public function __toString() {
return $this->content . '\r\n';
}
}
$text= new CleanOutput('Hello world!');
echo $text;
?>
The above would output "Hello world!" with a newline and carriage return appended at the end. There's ways to further encapsulate this, but they are outside the scope of my answer.
Edit:
As was noted, the above solution is slow/clumsy. Here's a more elegant solution using output buffering:
<?
function clean_up($foo) {
return $foo . '\r\n';
}
ob_start('clean_up');
ob_implicit_flush(true);
echo "Hello world!";
?>
This is faster and cleaner (although it technically doesn't 'override' echo).

Is there any difference between <?=$value?> and <? echo $value; ?>

Environment: Windows/7 + Apache/2.2.21 + PHP/5.3.8
File contents of test.php:
hello, <?=$test?>
File contents of index1.php:
<?php
$test = 'world';
require './test.php';
?>
File contents of index2.php:
<?php
global $test;
$test = 'world';
require './test.php';
?>
Output of index1.php is:
hello,
Output of index2.php is:
hello, world
When the contents of test.php is:
hello, <? echo $test; ?>
Output of index1.php and index2.php both are:
hello, world
So, my question is: Is there any difference between <?=$test?> and <? echo $test; ?> ?
No, there is no difference. Only one I think about is that <? is considered as short tag and might not work.
There is a little difference, that can be very, very annoying. If in php.ini you short_open_tag is set to false, you will receive a lot of errors. Otherwise, is exactly the same.
In every case, the last ; before ?> is optional.
There is no output differnce between <?=$x;?> and <? echo $x; ?> for that matter.
Even though i think this technique of including an active PHP file isn't really best practices in this specific condition.
Shai.

Php echo vs jsp style

Which is the fastest:
$content = "some html";
<div><?php echo $content?></div>
or
$content = "some html";
<div><?=$content?></div>
?
Doesn't matter.
<?= ... ?> won't work if short_open_tags are disabled and the version of php is older than version 5.4 though (which is unlikely).
But if you want maximum compatibility, use the <?php echo ...; ?> style.
no difference you could possibly ever notice. However, <?= ... ?> may not work across all servers because short tags is a setting that must be enabled. So you should as a best practice stick to <?php...?>
There would be no difference between full and short tags in terms of performance, but I recommend you utilize the full tags in case short tags are disabled. Additionally you can use single quotes '' if you are not echoeing any PHP variables.
Traditional echo statement
<?php echo "Hello World!"; ?>
Faster echo
<?php echo 'Hello World!'; ?>
If using PHP Variables
<?php echo 'Hello ' . $world; ?>
Or using a comma
<?php echo 'Hello ', $world; ?>

Capturing HTML to a string in PHP

Okay, so maybr I'm going about doing this entirely wrong, I probably am. But I would like to be able to take the HTML between a ... like so:
$str = ?>
... some HTML goes here ...
<?php ;
Am I completely off my rocker to think I can do this? I couldn't think of a way to put it into words so I could search it on Google, which is why I'm here...
You can use output buffering:
ob_start();
?>
... some HTML goes here ...
<?php
echo 'php outputs are captured too';
$str = ob_get_contents();
ob_end_clean();
Alternatively, if it's just a little bit of HTML (and no php code within), just write it down with one of the string formats like heredoc or nowdoc:
$str = <<<'NOWDOC'
... some HTML goes here
NOWDOC;
Look into heredocs and nowdocs. A heredoc looks like:
$str = <<<HTML
<div>This is some text!</div>
HTML;
// We're back in PHP.
echo $str;
If you specifically want to work with HTML, look into XHP.
Just wanted to add to phihag's answer.
It is possible to capture HTML with a function as well, including with anonymous functions:
<?php $bob = function() { ?>
... some HTML here...
<?php }; ?>
and later output $bob:
<?php $bob(); ?>
or capture the output of $bob somewhere else with output buffering:
ob_start();
$bob();
$str = ob_get_contents();
ob_end_clean();
PHP has a multiline, specially delimited string for such situations.
This talks about it a little.

Categories