Jump to content
MakeWebGames

Filtering out PHP code


Zeggy

Recommended Posts

Okay... So I have a file, and it contains PHP and HTML code.

I intend to include() this file at some point later in time, however, I am not sure what PHP code is in the file. So I need to find some way to remove or neutralise that PHP code.

How can I do this?

So far I've come up with this:

 

		$this->contents = str_replace('<?', '<?php echo \'<?\'; ?%TEMP%>', $this->contents);
	$this->contents = str_replace('?>', '<?php echo \'?>\'; ?>', $this->contents);
	$this->contents = str_replace('?%TEMP%>', '?>', $this->contents);

 

It seems to work fine. I just need to do the same for the ASP style tags and <script language="php"> tags, but... Does anybody spot any problems? Is there any easier way to remove PHP?

Link to comment
Share on other sites

Guest Anonymous

Re: Filtering out PHP code

It's a reasonable expression, however I suspect you may be asking the wrong question.

As for the modifiers "Uims"

U - Ungreedy -- ie match <?php ... ?> ... <?php ... ?> as 2 seperate entities rather than one

i - Ignore case - probably not needed, but force of habit

m - Handle multi lines -- important

s - Assume CR/CRLF is a normal character

As for testing it -- run it through all your scripts -- see what happens. It will fail in certain circumstances, as it relies on a closing ?> (which is not strictly necessary) and full open tags (<?php) over short open tags (<?).

Link to comment
Share on other sites

Re: Filtering out PHP code

I don't understand what you're trying to achieve here. You have a file that you know contains php and html, but you don't know what php it contains. That means you simply can't trust the contents of that file.

Now, a question in my mind is, do you know what html is supposed to be in that file? If so, why not make an html file to include?

Another question is, do you intend to ever use the php code in that include file?

Link to comment
Share on other sites

Re: Filtering out PHP code

Check out this PHP function Zeggy -> http://us2.php.net/file_get_contents

With that, you read an entire file into a string instead of the file being "included as code". You will be able to easily manipulate that file to your hearts content, and then just save it, perhaps using file_put_contents(). That last function can be read about here -> http://us2.php.net/manual/en/function.file-put-contents.php

And if all else fails, ask mdshare to link you to a post he made somewhere. I don't know exactly where it is, but he posted about using file_get_contents() as part of a lite php template system. ;)

Link to comment
Share on other sites

Re: Filtering out PHP code

Yes, I know, I use fopen to read the file and file_put_contents to save the file :)

The include part comes in later when the cached file is called. And I do need to use include because there's my own PHP code in there that needs to be run. The alternative is eval and that is just silly :P Then I use output buffering to capture the output from the included file.

Would you like to see the code I have? It might help you to see what I'm doing.

btw, I can't find the post you are referring to, but I'd like to see it. Do you have the link? :)

Link to comment
Share on other sites

Re: Filtering out PHP code

 

And if all else fails, ask mdshare to link you to a post he made somewhere. I don't know exactly where it is, but he posted about using file_get_contents() as part of a lite php template system. ;)

Not sure if it's relavant to this topic but here it is ...

here is a example function with file_get_contents() template related

function template($title,$meta_description,$meta_keywords,$meta_robots,$main_content){

 

function template($title,$meta_description,$meta_keywords,$meta_robots,$main_content){

if (!$title){
	$title = 'CE TopWebGames';
}
if (!$meta_description){
	$meta_description = 'description';
}
if (!$meta_keywords){
	$meta_keywords = $site_name.', blah, blah2, blah3, ...blah30';
}
if (!$meta_robots){
	$meta_robots = 'index, follow';
}

$main_content .= '';

echo str_replace(array("[+]title[+]", "[+]meta_description[+]", "[+]meta_keywords[+]", "[+]meta_robots[+]", "[+]main_content[+]"), array($title, $meta_description, $meta_keywords, $meta_robots, $main_content), file_get_contents('headerandfooter.txt'));
}

 

so main_content. = is basicly your echo for the main content of your template

title, meta stuff becomes dynamic as you asign for each page a new value, yet you use the same template file in my case simply headerandfooter.txt

so at my txt file ... (main content example)

 

...
<div id="maincontent">
  [+]main_content[+]
</div>
...

 

[ + ]main_content[ + ] gets nicely replaced by all that has to be echo'd

Link to comment
Share on other sites

Re: Filtering out PHP code

You can post the code if you want.

I'm back to my not understanding what it is that you want to achieve now though. Making a templating script I understand, but what you're doing seems to be outside the realm of just a templating script. Normally a template script doesn't care what php code is going to be run, it just does it's job dispassionately.

Link to comment
Share on other sites

Re: Filtering out PHP code

Even smarty gets rid of PHP (although you can set options for that).

getContents function:

	public function getContents()
{
	$tempname = md5($this->filename);

	if (NO_CACHE === 1)
	{
		$this->cache(); //Force recreating cache file each time
	}
	else
	{
		//If cache file exists, then check when it was last modified
		if (file_exists('cache/' . $tempname . '.php'))
		{
			$compare = time() - (60*60); //60 minutes ago
			if ($compare > filemtime('cache/' . $tempname . '.php'))
			{ //Cache file exists and expired, so use cache
				$this->cache();
			}
		}
		else
		{ //Cache file does not exist, so create it
			$this->cache();
		}
	}

	//Extract variables assigned
	extract($this->vars);

	//Include file with ouput buffering
	ob_start();
	include('cache/' . $tempname . '.php');
	$ret = ob_get_clean(); //Get contents of buffer and clear buffer

	return $ret;
}

 

Cache function:

	protected function cache()
{
	$tempname = md5($this->filename);

	$this->contents = str_replace('<?', '<?php echo \'<?\'; ?%TEMP%>', $this->contents);
	$this->contents = str_replace('?>', '<?php echo \'?>\'; ?>', $this->contents);
	$this->contents = str_replace('?%TEMP%>', '?>', $this->contents);

	foreach($this->vars as $var=>$value)
	{
		$this->contents = str_replace('{$' . $var . '}', '<?php echo $' . $var . '; ?>', $this->contents);
	}


	$template_header = '<?php /* Template \'' . $this->filename . '\' cached on ' . strftime("%d/%m/%Y %H:%M:%S") . ' */ ?>';
	$this->contents = $template_header . $this->contents;

	//Save as cached php file
	touch('cache/' . $tempname . '.php');
	file_put_contents('cache/' . $tempname . '.php', $this->contents);
}

 

Example of a template file:

<div class="category">
[url="category.php?id={$CAT_ID}"]{$CAT_TITLE}[/url]
</div>

{$BOARDS}

 

Example of a cached template file:

<?php /* Template 'themes/island/bits/category.tpl' cached on 05/11/2008 22:53:02 */ ?><div class="category">
[url="category.php?id=<?php echo $CAT_ID; ?>"]<?php echo $CAT_TITLE; ?>[/url]
</div>

<?php echo $BOARDS; ?>

 

Basically, the script reads the template file, replaces template variables with real PHP code, and saves the file. When the template needs to be displayed, it automatically includes the cached template file, thus removing the need for parsing the file to replace variables and what not. The caching is meant to benefit the server, not the user.

Link to comment
Share on other sites

Re: Filtering out PHP code

Now once you have the file cached, are you parsing it through the template again? Seems like it's cached so you don't have to do that. (I could be mistaken, I'm not a template person (mdshare is among others, so I don't claim to be expert or even anything more than noob on this one) )

Were does the need to remove any php come in?

Link to comment
Share on other sites

Re: Filtering out PHP code

PHP is removed in the cached function. It's still using the original code I started the topic with, I'll be changing it to nyna's regex as soon if I can get it working with all kinds of PHP start/close tags.

Once the file is cached and it needs to be displayed later, the template system doesn't parse the template variables anymore since it's been converted into PHP. It just extracts the variables assigned to the template and includes it.

This is the only part that's run if there's a cached file that hasn't expired yet:

      //Extract variables assigned
     extract($this->vars);

     //Include file with ouput buffering
     ob_start();
     include('cache/' . $tempname . '.php');
     $ret = ob_get_clean(); //Get contents of buffer and clear buffer

 

btw, if you're getting confused with the getContents function, ignore the part where NO_CACHE == 1, it's just a quick hack I'm using to stop caching (it creates a new cache file each time so that cache files stay up-to-date). I'll be changing that, but it's just something I'm using while developing.

Link to comment
Share on other sites

Guest Anonymous

Re: Filtering out PHP code

I'm tempted to ask why reinvent the wheel? There are plenty of good template engines out there - My one of choice being Smarty although I have to admit to having extended it somewhat.

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...