>  기사  >  php教程  >  php杂项函数(MISC)之__halt_compiler()

php杂项函数(MISC)之__halt_compiler()

WBOY
WBOY원래의
2016-06-06 20:13:541805검색

这个是我目前没有用过的一个函数,大多数人都没有必要使用这个函数,所以很少人了解他的用处。今天在stackoverflow上翻阅了一些相关的知识,分享给大家。 先看官方解释: 中断编译器的执行。常用于在PHP脚本内嵌入数据,类似于安装文件。 可以通过常量 __COM

这个是我目前没有用过的一个函数,大多数人都没有必要使用这个函数,所以很少人了解他的用处。今天在stackoverflow上翻阅了一些相关的知识,分享给大家。
先看官方解释:

中断编译器的执行。常用于在PHP脚本内嵌入数据,类似于安装文件。
可以通过常量 __COMPILER_HALT_OFFSET__ 获取数据开始字节所在的位置,且该常量仅被定义于使用了__halt_compiler的文件

再看两端代码和他们的运行结果:

vagrant@precise64:/var/www/test/misc$ cat exit.php 
<?php exit();
99999999
vagrant@precise64:/var/www/test/misc$ php -f exit.php 
PHP Parse error:  syntax error, unexpected $end in /var/www/test/misc/exit.php on line 4
vagrant@precise64:/var/www/test/misc$ cat halt.php
<?php
__halt_compiler();
9999
vagrant@precise64:/var/www/test/misc$ php -f halt.php
vagrant@precise64:/var/www/test/misc$

看到区别了吧!
exit()和__halt_compiler()方法都会退出代码的执行,但是使用exit()的文件会解释到文件的结束,如果遇到语法错误就会报错,__halt_compiler()则不会解释后面的代码。所以你可以再__halt_compiler()后面放任何你想放的东西(比如你银行卡账号和密码)而不用考虑语法的问题。

在__halt_compiler()出现的文件里面还会产生一个变量__COMPILER_HALT_OFFSET__,值是代码中断的位置的下一个字符,就是官方所说的”数据开始字节所在的位置”;
请看下面的代码:

vagrant@precise64:/var/www/test/misc$ cat halt_compile.php 
<?php // open this file
$fp = fopen(__FILE__, 'r');
// seek file pointer to data
fseek($fp, __COMPILER_HALT_OFFSET__);
// and output it
var_dump(stream_get_contents($fp));
// the end of the script execution
__halt_compiler(); 
the installation data (eg. tar, gz, PHP, etc.)
vagrant@precise64:/var/www/test/misc$ php -f halt_compile.php 
string(49) " 
the installation data (eg. tar, gz, PHP, etc.)
"
vagrant@precise64:/var/www/test/misc$

使用fseek方法直接移动到“the installation data (eg. tar, gz, PHP, etc.)”开始的位置,然后读取里面的内容。

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.