Latest Register Log In

+ Advanced Search

PHP in Templates

PHP in Templates
By
09/24/03 (Edited 03/10/14)

This is an advanced topic, for those who do some light PHP coding.

PHP can be used in any template, including custom templates. Simply put <?php at the beginning and ?> at the end of your PHP section. The one main point to be aware of is that you should not put any database or password info in this templated php -- if you need to use important info, save it in a file with a .php extension and then include that file into your template. Only files with .php extensions are safe... it would be easy for anyone to come along and read your template file by looking for /templates/default/yourtemplate.tpl on your site.

To use any preexisting variables from the script you will have to declare them as global first (example: global $thismember,$settings; ). When using your own variables, as of course the majority of users would be, this is a non-issue.

Here's a sample:
<?php
global $settings;
if ($settings->apacherewrite == 'yes') echo "Using mod_rewrite.";
else
echo "Not using mod_rewrite.";
?>

Please note that if you are including an external script in a php section and that script happens to change the database away from the WSN Links database, you may need to use "require 'config.php';" at the end of your php section to avoid errors.

Note that for simple uses, the conditionals syntax is both easier and safer (less error-prone as it corrects some of your mistakes) than PHP. Even for complex uses, calling a function through the template ({FUNC_NAME[parameters]}) is usually easier than using PHP.

Also note that you can mix template variables into your PHP to simplify it. For example,
<?php if ({LINKNUMBER} % 2) echo "link is even"; ?>
Warning: Be careful when mixing template variables with PHP, because you'll often create parse errors without realizing it. If the template variable contains quotes inside it, as most HTML will, you cannot safely quote it in your PHP.




Description For advanced users.
Rating
Views 3370 views. Averaging 1 view per day.