Keeping PHP code in database and running it
Archive - Originally posted on "The Horse's Mouth" - 2009-01-09 06:16:30 - Graham EllisThe software for these articles lets me enter HTML and keeps it in a database. If I want to add PHP, that gave me a problem as the data (HTML) was simply read from the database and passed to my client's browser without being parsed for <?php to ?> sections. But problem solved in two different ways!
The current page is generated as I write the blog, and is saved on the server as a regular .html file. We have simply instructed our server that in this area, when serving files ending in .html it is to put them through the PHP interpreter - that's a line like
AddType application/x-httpd-php .html
in my .htaccess file.
Our archive pages are not stored- they're not called up so often, so we can afford to generate them on the fly. In addition, the menu of "other available articles" changes dynamically as new articles are added - so we cannot store the pages unless we chose to rebuild all 2000 every time an article was added or updated.
Here is the line of PHP that we used on the archive pages to include the HTML within the page:
$bodder = nl2br($row[entry_text]);
When we wish to include PHP in there too, we have a problem - it's going to be passed right to the browser, and as PHP source too. Here is our solution:
ob_start();
eval("?"."> $row[entry_text] <"."?php ");
$yeahz = ob_get_contents();
ob_end_clean();
$bodder = nl2br($yeahz);
a) The use of eval let me actually run the code from the database. However, the output would go straight to the browser which isn't what I want so ...
b) The ob_start buffers the output from the eval, the ob_get_contents returns the data to me from that buffer, and the ob_end_clean deletes the information from the output buffer and turns buffering off. So I have used the built-in facilities to trap the output from the PHP.
Does it work? Yes ... but I do need to check XML feeds as well if I start making heavy use of this. I suspect I need to parse them through PHP - not a big deal. Let me test it. The current time is = date ("H:i") ?> and the date is = date("jS F Y") ?>. It is a = date("l") ?>. [[Those sentences should have changed for you to reflect the time on the server when you called it up]].