PHP TIPS:关于状态函数应用file_exists()和clearstatcache();

王朝php·作者佚名  2006-04-18
窄屏简体版  字體: |||超大  

PHP TIPS:关于状态函数应用

不知道大家注意到没有,在使用PHP的状态函数时,有时会遇到些奇怪的问题。

比如下面程序在使用file_exists()函数时出现的状况:

<?php

$myfile = "/usr/local/somefile.txt";

if(!file_exists($myfile)){

$fp = fopen($myfile,"w");//创建一个

}

if(!file_exists($myfile)){

echo "The File exists";

}else{

echo "The file does not exists";

}

?>

运行后发现,运行结果和下面程序一样,输出结果是:The file does not exists

<?php

$myfile = "/usr/local/somefile.txt";

$exists = file_exists($myfile);

if(!$exists){

$fp = fopen($myfile,"w");//创建一个

}

if(!$exists){

echo "The File exists";

}else{

echo "The file does not exists";

}

?>

查了资料才发现,原来PHP对此类状态函数做了CACHE处理。

由于状态函数在调用时很占内存,调用的结果就被保存在CACHE中以便快速存取。

因此,对于上面程序想要达到预期的结果,必须使用clearstatcache()函数清除cache。

<?php

$myfile = "/usr/local/somefile.txt";

if(!file_exists($myfile)){

$fp = fopen($myfile,"w");//创建一个

}

clearstatcache();

if(!file_exists($myfile)){

echo "The File exists";

}else{

echo "The file does not exists";

}

?>

PS:以上程序在PHP4下调试。

需要调用clearstatcache()的状态函数有:stat(),lstat(),file_exists(),

is_writeable(),is_readable(),is_execntable(),id_file(),is_dir(),

is_link(),filectime(),fileatime(),filemtime(),fileinode(),filegropu(),

fileowner(),filesize(),filetype(),fileperms();

另外,状态函数的结果仅在程序的执行周期内保存在CACHE中,如果对一个特定文件只调用一次状态

函数就没有必要清除cache了。

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有  導航