エスケープ処理(escape)
「escape」はHTMLやURLなどのエスケープ処理を行う場合に使用します。ユーザーから入力された値をそのまま表示するように記述した場合、クロスサイト・スクリプティングなどのセキュリティ上の問題が発生します。「<」や「&」などのHTMLタグを適切にエスケープしてくれます。書式は次の通りです。
{$変数名|escape[:エスケープ種類[:文字コード]]}
エスケープの種類は次のようなものがあります。
html htmlall url urlpathinfo quotes hex hexentity javascript mail
エスケープ種類を指定しなかった場合のデフォルトは「html」です。
具体的には次のように記述します。
HTMLは {$name|escape:"html"} です
エスケープ一覧
「html」を指定した場合は次のようなエスケープ処理が行われます。
< -> < > -> > " -> " ' -> ' & -> &
「quotes」を指定した場合は次のようなエスケープ処理が行われます。
'sample' -> ¥'sample¥'
「mail」を指定した場合は次のようなエスケープ処理が行われます。
homge@hoge.hoge -> hoge [AT] hoge [DOT] hoge
サンプルプログラム
では簡単なサンプルプログラムを作成して試してみます。
<?php
require_once('Smarty.class.php');
$smarty = new Smarty();
$smarty->template_dir = 'd:/smartysample/modifier/templates/';
$smarty->compile_dir = 'd:/smartysample/modifier/templates_c/';
$smarty->config_dir = 'd:/smartysample/modifier/configs/';
$smarty->cache_dir = 'd:/smartysample/modifier/cache/';
$smarty->assign('title', '修飾子のテスト');
$smarty->assign('htmltext', '<p>HTMLの"テスト"</p>');
$smarty->assign('quotestext', "HTMLの'テスト'");
$smarty->assign('mailtext', 'hoge@hoge.hoge.hoge');
$smarty->display('sample5-1.tpl');
?>
上記を「sample5-1.php」の名前で「(Apacheドキュメントルート)¥smarty¥modifier」に保存します。
{* Smarty modifier/sample5-1.tpl *}
<html>
<head>
<title>Smarty Test</title>
</head>
<body>
<h1>{$title}</h1>
{$htmltext|escape}
<p>{$quotestext|escape:'quotes'}</p>
<p>{$mailtext|escape:'mail'}</p>
</body>
</html>
上記を「sample5-1.tpl」の名前で「D:¥smartysample¥modifier¥templates」に保存します。
そしてブラウザから「http://localhost/smarty/modifier/sample5-1.php」へアクセスして下さい。
「html」は見た目は変換されていませんが表示されたHTMLページのソースを見てみると変換されていることが分かります。
( Written by Tatsuo Ikura )
PHPBook