Display any website source code for copy/paste - php

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

Related

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/

Stop PHP parsing but output the rest of the file

I'm developing a web application where an html page is created for the user. The page could include anything that the user puts in it. We take these pages and add a little PHP at the top to check some things before outputting the actual html. It would look kind of like this:
<?php
require 'checksomestuff.php';
// User's html below
?>
<html>
<!-- user's html -->
</html>
Is there a way to stop PHP from parsing anything after my require? I need the html to be outputted, but, since the user can add anything they want to the html, I don't want any user-added PHP to be executed. Obviously that would be a security issue. So, I want the user's html to be outputted, but not parse any PHP. I would rather not have to put the user's html into another file.
One sensible way would be to offload the user created content to another file and then you should load this file (in your main php file) and output it as is - without parsing it as PHP.
There are many other ways to do this but if creating another file does the job for you then thats probably the best way forward.
UPDATE: Really must read last line of question!
You could encode the html into a variable using base64 encoding which you then just print out the decoded string.
If you don't store the file data in a php file, say n a txt or html file, the php won't be evaluated.
Alternatively you could read the file via file_get_contents() or by some other means which doesn't involve evaluating php.
Though I'm still tempted to ask why you want to do this (particularly this way), it sounds to me like one of the only things that can help you is the special __halt_compiler() function...
That should prevent it from executing the rest of the page, and may or may not output the rest of it. If not, well, read the first (and currently only) example in the PHP's manual for that function (linked above) for how to do it manually.
The only trouble I see with this method is that you'd probably have to have that code in every file you want to do this for, after your require.

Saving HTML page to MySQL Database and then inserting code into that HTML and seeving it up again

I'm trying to build something similar to the "Try on your site" on http://www.mywebpresenters.com/
I want to let users enter in their URL, then I need to save the HTML of that URL/Page to a MySQL database using PHP. I then need to insert a div containing more code and then serve up the whole lot to the user again.
I have done this using an IFrame but I'd like to do it better.
Can anyone shed light on this? Also, This will be used on a WordPress site if that adds in anyway.
Thanks in advance,
Barry
If you want to save the whole html page in the database use the smarty. It simply fetch a html file in a variable like
$myvar = smarty->fetch('htmlfile');
now you can simply save the $myvar into the sql.
Unless you are prepared to parse the HTML and remove the head/body tags of the scraped page, than an iFrame is the way to go. You could probably use a find/replace algorithm when you retrieve the stored HTML from the server to insert the containing code that you need into the correct location.
The only way I could personally think of doing this is having them upload the page to your site and then doing a mysql query using PHP to store it into database. Then using the PHP 5 DomDocument model to take that same code and save it as a dynamic page.
Well actually, you can do it two ways. You can use PHP cURL library to get the url of the page and simply parse and save the HTML code to the database as well.
To present it in a div you want to use javascript and get the div a target _top attribute so window.open can load the content in that page.
You don't even need WordPress for this to be honest. This can be done by scratch.

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!

PHP to Javascript and back to HTML design problem

(1) On server side I have a piece of PHP code that takes data from DB and converts them into a sort of Javascript array/matrix, let's just simply call it the PHP_OUTPUT
(2) On client side I have a piece of Javascript code that takes the PHP_OUTPUT and renders it as an HTML table.
Unfortunately Google does not read Javascript, so if I want Google to see the contents of the HTML table, I must write down in page the real HTML of the table. So now I need a NEW piece of PHP code to create by itself the SAME HTML table created by the Javascript code.
One way is obviously to rewrite in PHP all the Javascript code that renders the HTML table. Code rewriting is a sport that I don't like much.
Another way (I don't know if possible) is in some way to:
a) have (1) to pass the PHP_OUTPUT to (2),
b) then (2) creates the HTML table and sends (in some way) back the HTML source of the table to server,
c) finally the NEW piece of PHP code on server just writes down the source with a simple echo.
It's convoluted, but this would reduce the amount of code to be written to almost zero.
But is there a simple way to do this kind of stuff?
Hope you understand what I wrote, plz comments to ask for explanations.
Thanks for any answer.
If you are able to create the HTML on the server side, then why do you need JavaScript at all? I would say the simplest way, would be to use your PHP code that creates the HTML that you need and get rid of the JavaScript all together.
Could you not simply have the PHP also dump the DB data into a hidden div of some sort? If it is simply for indexing purposes, it does not necessarily have to be in a human-readable table format, right?

Categories