How to execute PHP code stored in a database

Webpage extractionImage ExtractorLink ExtractorCSS / Stylesheet ExtractorInline CSS to ClassesKeyword Extractor
SERP specificSERP rank CheckerSERP rank DominationSERP rank Comparison
MiscMultiSearchDuplicate Content FinderConvert / Text Transform
Otherjquery.optionBox pluginA note about browsers
ArticlesScraper with PHP and jqueryHow to parse SERPs in jquery► How to execute stored PHP

About our world leading company

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

<?php $recentProducts = new recentProducts(); $recentProducts->draw(); ?>

More about the company

... ...

I encountered this problem while developing an oldschool company website which besides products, galleries and so on, also included a set of static HTML pages. My goal was to make the website as search engine friendly as possible, therefore I wanted the ability to include some dynamic PHP generated content to the static pages.

Of course, you could do that in AJAX, but then the search engines would be unable to index the dynamic content. Also, it could be done with a system of "headers and footers", but this would make the static page concept too complex, and I really wanted to include different PHP according to the static page being loaded.


The solution

I found the solution by taking a good look at PHP's built-in function eval, and the rest was quite easy. Eval() is a specialized language construct that executes a piece of code. The function below let you execute stored PHP on the fly :

function include_PHP($text){
	while(substr_count($text, '<?php') > 0){             
		list($html, $text) = explode('<?php', $text, 2); 
		echo $html;                                      
		list($code, $text) = explode('?>', $text, 2);    
		eval($code);                                     
	}
	echo $text;                                          
}

The function simply loops trough the content of the stored page, evaluate PHP inside <?php and ?> and renders everything else as normal pre-formatted HTML. The very good (but also dangerous) thing about eval() is that it is not working in a "sandbox", but within the current scope. By that the stored PHP can access exactly the same globals, classes and so on, as if it was executed like a "normal" .PHP-page.

So now I simply run the content of a static page trough the include_PHP-filter, if a flag telling the page contains PHP, like this :

	...
	switch ($staticPage->is_php) {
		case false : echo $staticPage->html; break;
		case true : include_PHP($staticPage->html); break;
	}
	...

Hope this was helpful. Enjoy!



blog comments powered by Disqus