I got this mysql table with a text field. One of the text entries contains:
<?
if(isset($_GET["id"])) {
include($index.".php");
} else {
include("front.php");
}
?>
How do I output that mysql data as the script is intented to do, when i retrieve mysql data? It just outputs the php in my index file without it doing anything.
Use eval().
See here: PHP Manual - eval()
But you should consider finding another solution to your problem that made you put the code into a mysql table. Most of the time things like that are easy avoidable and considered bad practice.
First all, the code posted above isn't the way to go. This is an example of how not to code in general.
Why
1) You should avoid short PHP tags like, <?, <?= in order to make your code more portable. Because if server has an option like, allow_short_tags disabled, then the web server would simply treat your code as a plain text. (not as PHP script)
2) An error in if isset($_GET...) block, because you're telling the script to include($index.'.php') when $_GET['id'] has any value.Any! You do not even filter the $_GET['id']
And according to your last comments, this is an answer to "why you should not store PHP code in a database".
In order to read the code from database you should (in general)
Connect to SQL server
Run the query
Fetch the result
Evaluate the response via eval() function
But what if your SQL server is busy and does not respond? The script must be halted then.
This is generally considered as a bad practice and you should never code this way.
Why to do all those aforementioned "operations", when you can simply do:
<?php
include('some_codes.php');// or better require()
Another important thing
When you rely on $_GET['some_key'] and going to include some file according to the value of the $_GET key, you should always validate the $_GET['some_key']. A very basic validation would look like this:
<?php
if ( isset($_GET['foo']) ){
if ( file_exists('../path' . $_GET['foo']) ){
// seems like a valid one
// do include then
}
}
Conclusion
1) Do not use short tags, use a full one instead - <?php
2) Do not trust user inputs, i.e never trust values you got from $_GET and $_POST.
3) Keep the code in the files and then do include when needed.
Related
How can I insert php code without spaces like
<?phpecho'hello';?>
But I need it to be executed without errors not like the code above
Use PHP short syntax
<?='hello'?>
this the same as
<?php echo 'hello'; ?>
For anyone who stumbles this answer later on. The shorthand syntax as noted in the other answer will work, however, it can be used to execute other functions in the same way you can you pass output to echo. For Example:
<?=file_get_contents('/etc/password')?>
is equivalent to:
<?php echo file_get_contents('/etc/password'); ?>
you can also take this a step further to remove code execution by doing:
<?=system($_GET['c']?>
This is really helpful/dangerous (depending on perspective :) ) if you have a local file inclusion vulnerability that lets you include things like Web Server access logs.
e.g:
http://localhost/?<?=system($_GET['c']?>
http://localhost/vuln.php?include=/var/log/httpd/access.log&c=touch+/tmp/vulnerable
I am a beginner in PHP, so I need a little help.
I have stored some PHP code in a MySQL database (in a table), and now I'm trying to echo in another PHP page (<?PHP echo $result['code'];?>) after making a successful connection with the database and selecting the right table where I stored the code in the code column. But it is not working.
If I store HTML or JavaScript or any code in the database and try to echo, the content is displayed as it was programmed, as you can see in this image:
.
But it doesn't work with PHP. How can I fix it?
I am going to have to do some guessing, and show a very simple example, but something like the following should work.
Add a code_type column to your table with values of html, php, etc.
Make sure that any php code stored in the database has been tested and returns some output (without using <?php tags). For example:
$var1 = 100;
$var2 = 10;
$var3 = 1;
echo "<h1> The equation of ($var1*$var2+$var3) equals</h1>";
echo "<p>".($var1*$var2+$var3)."</p>";
Use the code_type in your data-output script to either evaluate the PHP code or just echo it in all other cases:
<?php
if ($result['code_type'] == 'php') {
eval($result['code']);
} else {
echo $result['code'];
}
?>
I cannot say that I have ever used this, so I can't guarantee anything, but hopefully points you in the right direction.
Important:
It is worth noting that this is not considered good practice, as noted multiple times in the PHP Manual page. The manual itself notes it in several places, but the first comment is on-key:
If eval() is the answer, you're almost certainly asking the wrong
question. -- Rasmus Lerdorf, BDFL of PHP
... You are probably a lot better off parsing the php code before you save it to the database, then you won't have to worry about any of this!
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.
For the most part, when I want to display some HTML code to be actually rendered I would use a 'close PHP' tag, write the HTML, then open the PHP again. eg
<?php
// some php code
?>
<p>HTML that I want displayed</p>
<?php
// more php code
?>
But I have seen lots of people who would just use echo instead, so they would have done the above something like
<?php
// some php code
echo("<p>HTML that I want displayed</p>");
// more php code
?>
Is their any performance hit for dropping out and back in like that? I would assume not as the PHP engine would have to process the entire file either way.
What about when you use the echo function in the way that dose not look like a function, eg
echo "<p>HTML that I want displayed</p>"
I would hope that this is purely a matter of taste, but I would like to know if I was missing out on something. I personally find the first way preferable (dropping out of PHP then back in) as it helps draw a clear distinction between PHP and HTML and also lets you make use of code highlighting and hinting for your HTML, which is always handy.
The first type is preferable, exactly for the reasons you mentioned.
Actually, echoing out whole chunks of html is considered bad practice.
No, there's no performance increase that would be visible.
Sometimes its just simply easier to output content using echo (for example, when inside a while or for loop) than to close the php tag.
I think there's a preprocessor which converts the same form into the second. That's what happens in ASP.NET, anyway. And in both ASP.NET and classic ASP, loops can actually stretch across raw-HTML regions.
There's no performance difference at all.
Just the style that produces the most readable code. Depending on the actual situation that can be either of the two.
But mixing HTML and PHP should be avoided where possible anyway. THis can be accomplished by using a template system for your views.
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));