Run PHP code collected from database - Without Eval - php

I want to query a string from my db, which's a PHP code and run it. All solutions I've seen on the Internet is eval(). But I know that Eval is Evil.
So is there any alternative? I've thought of converting my PHPcode into data:base64, and feed it through the require_once() function. But couldn't find this successful. Will this way or anything relative to this work? My platform is Wordpress.
I've heard people saying storing PHP code in database is dangerous. But is it safe to store just raw HTML code instead of PHP ?

For executing php eval is the way to go. And it is not recommended.
It is safe to store html in the database. WordPress does so by itself.
Maybe what you want you can do with a shortcode. Which is save.

Related

Process content from database as php

I'm not exactly sure what I need to search for in Google and have been struggling with this for a while.
I wrote my own CMS for a project and am stuck with processing content stored in the database, for example.
This is a link to a related page.
In the above example I'm getting a page url by its ID, this way it doesn't matter if the url changes, it will always be up to date.
The issue is PHP sees it as a string and will not process it.
Im working around the issue by writing the contents to a file, using PHP include on the file, and then deleting the file. I don't see this as an efficient and would like a better solution.
PHP reads that content as a string because it is a string.
To make your string function as PHP, you'll need to use PHP's eval() function.
// The string that is loaded from the DB, or wherever
$string = 'This is a link to a related page.'
// Run the string as PHP code (notice the "echo" command)
eval("echo {$string}");
This can be very dangerous, however! If you're going to do this, be very certain you know what string is being executed! Because the eval() function will run any PHP code that is placed in it! Even site-destroying-dog-kicking PHP code!
More about the eval() function can be found in the PHP Docs for eval()
--
I don't know your exact scenario, but I would generally advise against using eval() wherever possible. There is normally a safer way to doing something than using the eval() function.

How to go about editing a php file to change values?

I would like to write a script to edit a css file or maybe even a slideshow for instance where a form will update the variables in my php document. I've been doing some reading and some say editing a php file directly is bad news due to security issues and to use xml.
I am not connecting to databases or anything like that. So my question is is this correct to write script to directly write/update a php file to changes its variables?
Thank you.
if you can correctly sanitize your input then it is a usable aproach. The worst that can happen is code injection. So do check for variable length and content very strictly. It is like eval(); only worse, as everyone else will run it to. If there are only variables to change you might consider using an .ini file for configuration. And Use the data in that from your PHP script
In general you should not run PHP scripts as a user with permissions to write to its own executable code; it means any file write vulnerability immediately escalates to a code execution vulnerability.
Writing dynamic data into a PHP file is risky. You would need to know how to serialise/escape any value to a PHP literal exactly; any error could result in code execution. Watertight code generation is in general a tricky thing.
There is almost certainly a better way to approach whatever it is you are doing. Putting data in a static store such as a config file or database, and reading the data at run-time, would seem to be the place to start.

How I could Render PHP code from MySQL database?

I am creating some kind of custom CMS (home automation).
Well I am not a PHP developer - just hobbyist.
What I am trying to achieve is:
In my index.php page I have something like:
"<?php echo $pageBody; ?> "
PageBody I am fetching from Database, well it works well for HTML, JS. But it doesn't work with PHP code source.
I done some research I believe this is related to PHP security restrictions.
My question: Does anybody would be able to provide safe sample (cannot find any samples like this) - how I should do this.
I am trying to insert some php code and render it eventually via browser:
<div id="outer">
<div id="inner">
***PHP Code should go here***
</div>
</div>
At the minute - it is being rendered as text. However I can render properly HTML and JS.
My preferable way would be - as much as possible secure.
Many Thanks Guys!
When you retrieve PHP code from a database text field, the PHP interpreter does not "know" that it should parse the data as a PHP script. To the PHP interpreter, the data in that field is no different from any other data -- it is all strings without any special significance.
You could use eval (docs) to accomplish this if you're dealing with pure PHP scripts. Be forewarned: eval is considered "evil" because using it comes with risks, especially if your users will have any input as to the content of the database.
In your case, it sounds like you want to parse mixed PHP and HTML that is stored in a database field. In order to do this, you'd need to write the database data into a file, then include it so the PHP interpreter can do its thing. You should implement some kind of caching mechanism in this process, otherwise it might become heavy on your server with many users. You may also want to use output buffering (docs) to capture the output instead of immediately sending it out.
Briefly, you'd want to do something like this:
$content_from_db = "<h1>Hello <?php print 'Clarisse'; ?></h1>";
$identifier_from_db = '12'; // like the primary key from the table
$file_handle = fopen('cached_content/CACHE_'.$identifier_from_db.'.php', 'w');
fwrite($file_handle, $content_from_db);
fclose($file_handle);
// here is where you'd start output buffering, if you're going to do that (optional)
include('cached_content/CACHE_'.$identifier_from_db.'.php');
// and then here you retrieve the output buffer's content (optional)
Please note that this is not a "traditional" way of including dynamic content, and the above code is not production-ready. Without knowing your use case, I can't say for certain, but this idea of storing PHP code in the database is a rather unusual way to proceed.
Another alternative to rolling your own is the smarty template library. Check it out here: http://www.smarty.net. With smarty, you can write a resource plugin to pull the templates from the database. It would look something like the code above (more info)
Documentation
fwrite - http://php.net/manual/en/function.fwrite.php
include - http://php.net/manual/en/function.include.php
PHP basics on theopensourcery.com - http://theopensourcery.com/phpbasics.htm
Server-side scripting on Wikipedia - http://en.wikipedia.org/wiki/Server-side_scripting
eval - http://php.net/manual/en/function.eval.php
Output Control (buffering) - http://php.net/manual/en/book.outcontrol.php
Smarty - http://www.smarty.net
to execute PHP that you store in a string (or database) you can use the eval function, but be careful it could be somewhat dangerous.
You can't render (probably you mean execute) php code in the browser, because php scripts execute on the server and then the output is sent to the browser. By the time the browser recieve the response, script has already finished execution.
You can fetch the code from database and use eval() before sending the output. But you must be aware of drawbacks from this approach.
Browser cannot render (execute) PHP code. PHP is something that the server executes and sends to the browser as plain HTML to display.
For testing purposes you can download and install WAMP thats the most hassle free one stop solution for development.
link : http://www.wampserver.com/en/

Is it possible to execute PHP code returned from a MySQL query result?

The issue I am having is as follows: I have a MySQL table that contains details for page content I wish to display on my site. The content for one of my pages however I wanted to contain some actual PHP code to be executed, not just printed as a string. For example:
require_once("Class.php");
Class::Function("Some Text For a Parameter");
I want this code to execute somehow when the sql query is returned but as it stands, it just prints that text out. Is there a way to achieve what I want?
Thankyou in advance for your time,
Regards,
Stephen.
You can do it with eval(), but you shouldn't.
they are several ways to achieve the storage of dynamic elements :
eval(str) : you can evaluate as php code any string coming from you database. This is not very wise if what is stored in the database comes directly from a user input field. You never know what is going to be inserted and it could potentially be harmful code (harmful to the security of your server)
save / include : you could save what comes from your database in a temporary file and include() that file in-place in your php code. This does not seem to be secure either if anyone can store anything in your database
use a templating engine that has a reasonnable command footprint like smarty or mustache. you can store the templates in your database and execute them. If you trust the implementation of the templating language (and disable native php calls inside smarty for example) the template will need to have a correct syntax before execution can begin
As a general rule of thumb, it is very hard to protect such dynamic php code inclusion, so it should be considered as bad practice.
You should consider a DSL (domain specific language) for which you will trust the parser/compiler and execution engine.
If security is not a concern (because your application will not be public for example) then it can be perfectly valid and effective to store php fragments in the database.
I hope this will help you
Jerome Wagner
I do a variation of this in my personal CMS by doing a bbcode of sorts. I enclose php to evaluate inside of [code][/code] tags, then when displaying I have a function that uses regular expressions to grab the contents of code inside the [code] tags to run. It in turn builds the code such that it closes the text echo, runs the script, then starts the text echo again. Perhaps the explanation is a bit simplistic, but you get the idea.
I would definitely avoid eval!

Display any website source code for copy/paste

I have a website displaying data from MySQL in a php file (/something.php).... i want to copy the source code of that page as HTML so i can use it in a textfield box so users can copy paste that code...
It's almost like an HTML generator using info from mySQL, so users can custimize each HTML code.
I have everything covered... except the display HTML thing.
echo htmlspecialchars(eval(file_get_contents('path/to/your/file')));
Eval is generally frowned upon however but this is a quick and easy solution.
You need to escape the HTML into HTML entities. For instance, convert < into <.
You need to actually request the page from the web server, not simply read its contents in order for the PHP to execute and produce the result. That is, if I understand correctly that PHP (the file you were simply reading) is querying the database to actually fetch the desired HTML to display.
So, something like (if permitted) file_get_contents("http://url_of_php_file_you_were_simply_reading_not_requesting"); , then of course run that through htmlspecialchars();
Better to just use CURL to stay portable when requesting the page.
There's a php function htmlspecialchars you should look into.
For rendering check either eval (quick & dirty) or ob_start and friends (the more complex way to do it, though safer and generally supported by more hosters).

Categories