Sunday, June 20, 2010

[Article] How to hide the smarty template files

The first and easiest approach is to put your template directory outside of the root directory (www in wamp, htdocs in xampp). However several hosting providers do not allow this.

You can also specify a .htaccess file, as this:
<Files ~ "\.(tpl|inc|cfg)$">
order deny,allow
deny from all
</files>

(thanks for scuzzy from Smarty forum for this code)

Other way is to give a name to your template file or template directory that cannot be guessed (like a hash code). However all of these have weaknesses. What if you can't specify an access file and your provider haven't blocked the directory listing (in the latter case you could also use a blank index.php).

At last I present the best solution. Create every template file with the following structure:

<!--{if $does_not_exist}-->
<?php
die("You can't access the tamplete file");
?>
{else}
<html>
<body>
Hello, {$name}!
</body>
</html>
{/if}


And save it with a .php extension, instead of a .tpl. If someone tries to access this file directly, he will only see the "You can't access the template file" string. Viewing the source he will also see the "<!--{if $does_not_exist}-->" comment, but that won't hurt anyone. The code works like this: the template engine will check for the variable, and because it wont find the variable specified (hopefully) it wont execute the php snippet. If accessed directly, the Smarty snippet wont be parsed, hence the first PHP code will hide the rest of the file returning with a message. Works as a charm.

EDIT: You could also try to play with the idea, for example, moving the comment inside the PHP, but even like this some wierd comments will appear:

<?php
//{if $does_not_exist}
die("You can't access the tamplete file");
?>
{else}
<html>
<body>
Hello, {$name}!
</body>
</html>
{/if}