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

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了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值