3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

PHP の `eval()` の HTML モードと PHP モード切り替え時の罠

Last updated at Posted at 2017-09-05

PHP の eval() は評価させる文字列内で HTML モードと PHP モードを切り替えることができます。 evalに渡された文字列は ?> 以降から HTML モードとして解釈され、再び <?php が出てきたらその後ろの文字列は PHP として解釈されます。しかし、 <?php の後ろが文字列の終端だとその <?php は HTML として解釈されます。

<?php がPHPモードに切り替わらない

hoge.php
eval('echo "hoge"; ?> hoge <?php');
hoge.phpの出力
hoge hoge <?php

後ろに何かついているとPHPモードに切り替わる

fuga.php
eval('echo "fuga"; ?> fuga <?php echo "fuga";');
fuga.phpの出力
fuga fuga fuga

空白がある場合もPHPモードに切り替わる

bar.php
eval('echo "bar"; ?> bar <?php ');
bar.phpの出力
bar bar 

<?php だけだとそもそもPHPとして正しくない

末尾に改行を含まない
echo -n "<?php" > index.php
php index.php #=> "<?php" が出力される
末尾に改行を含む
echo "<?php" > index.php
php index.php #=> なにも出力されない

それはさておき、渡すコードは PHP として有効な形式でなければなりません。

3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?