php code in smarty

Your can write your php code in your smarty template and its true. But you have to check for some global settings of smarty to do this.

There is a smarty variable “$php_handling” that decides how the php code should be handled by the smarty engine. The possible four values of this variable are:

  • SMARTY_PHP_PASSTHRU – Smarty echos tags as-is.
  • SMARTY_PHP_QUOTE – Smarty quotes the tags as html entities.
  • SMARTY_PHP_REMOVE – Smarty removes the tags from the templates.
  • SMARTY_PHP_ALLOW – Smarty will execute the tags as PHP code.

from the above four SMARTY_PHP_PASSTHRU is the default setting.

you can change this variable value to work with php code as follows:


$smarty = new Smarty;

$smarty->php_handling = SMARTY_PHP_ALLOW;


after enabling this varialbe to allow the php code in smarty, to write php code in smarty you just have to write the php code inside the {php}{/php} tags.

i.e. {php}

//your php code here


One more thing, there is another variable ‘$security_settings’.

These settings are used to override when security is enabled. The possible settings are:

  • PHP_HANDLING – true/false. If set to true, the $php_handling setting is not checked for security.
  • IF_FUNCS – This is an array of the names of permitted PHP functions in IF statements.
  • INCLUDE_ANY – true/false. If set to true, any template can be included from the file system, regardless of the $secure_dir list.
  • PHP_TAGS – true/false. If set to true, {php}{/php} tags are permitted in the templates.
  • MODIFIER_FUNCS – This is an array of the names of permitted PHP functions used as variable modifiers.
  • ALLOW_CONSTANTS – true/false. If set to true, constants via {$} are allowed in the templates. The defaults is set to “false” for security.

to change or access these setting you can write the code as follows:

$smarty->security_settings['ALLOW_CONSTANTS'] = true;